ApplicativeSwift
ApplicativeSwift copied to clipboard
Provides the operators to realize the applicative style for Swift, which is used in Haskell.
ApplicativeSwift
ApplicativeSwift provides the operators to realize the applicative style for Swift, which is used in Haskell.
let a: Int? = 2
let b: Int? = 3
let result: Int? = (+) <^> a <*> b // Optional(5)
Purpose
We use a lot of Optional
values in Swift. Sometimes we want to apply operators or functions to 2 or more optional values. But it is too complicated.
let a: Int? = 2
let b: Int? = 3
// How to calculate a + b? (wants nil if a or b is nil)
// Too complicated
let result: Int? = {
if let a0 = a {
if let b0 = b {
return a0 + b0
}
}
return nil
}()
In Haskell, it can be done easily in the applicative style.
-- Haskell
(+) <$> a <*> b
ApplicativeSwift provides such operators for Swift. Because the letter $
cannot be used for operators in Swift, ApplicativeSwift provides <^>
instead of <$>
. Therefore a + b
can be calculated in the following way.
// Swift
(+) <^> a <*> b
Usage
// Optional
let a: Int? = 2
let b: Int? = 3
let c: Int? = 5
let d: Int? = 7
let e: Int? = 11
let f: Int? = 13
let g: Int? = 17
(+) <^> a <*> b
sum3 <^> a <*> b <*> c
sum4 <^> a <*> b <*> c <*> d
sum5 <^> a <*> b <*> c <*> d <*> e
sum6 <^> a <*> b <*> c <*> d <*> e <*> f
sum7 <^> a <*> b <*> c <*> d <*> e <*> f <*> g
// Array
(*) <^> [1, 2] <*> [3, 4]
// Currying
curry(+)(2) <*> .Some(3)
[curry(+), curry(*)] <*> [1, 2] <*> [3, 4]
Installation
Carthage
Carthage is available to install ApplicativeSwift. Add it to your Cartfile:
github "koher/ApplicativeSwift" ~> 2.0.0
Manually
Embedded Framework
For iOS 8 or later,
- Put ApplicativeSwift.xcodeproj into your project in Xcode.
- Click the project icon and select the "General" tab.
- Add ApplicativeSwift.framework to "Embedded Binaries".
-
import ApplicativeSwift
in your swift files.
Source
For iOS 7, put Applicative.swift into your project.
License
The MIT License