Skip to content

Instantly share code, notes, and snippets.

View macbaszii's full-sized avatar
🏠
Working from home

iMacbaszii macbaszii

🏠
Working from home
View GitHub Profile
Optional(20) >>- half >>- half >>- half
// => .None
// For Optional
func >>-<T, U>(a: T?, f: T -> U?) -> U?
// For Array
func >>-<T, U>(a: [T], f: T -> [U]) -> [U]
Optional(3) >>- half
// .None
Optional(4) >>- half
// 2
Optional.None >>- half
// .None
func half(a: Int) -> Int? {
return a % 2 == 0 ? a / 2 : .None
}
infix operator >>- { associativity left }
func >>-<T, U>(a: T?, f: T -> U?) -> U? {
return a.flatMap(f)
}
func curriedTimes(a: Int)(b: Int) -> Int {
return a * b
}
curriedTimes <^> Optional(5) <*> Optional(3)
curriedAddition <^> Optional(2) <*> Optional(3)
func curriedAddition(a: Int)(b: Int) -> Int {
return a + b
}
curriedAddition <^> Optional(2) <^> Optional(3)
// => COMPILER ERROR: Value of optional type '(Int -> Int)? not unwrapped; did you mean to use '!' or '??'
[ { $0 + 3 }, { $0 * 2 } ] <*> [1, 2, 3]
// => [ 4, 5, 6, 2, 4, 6 ]
Optional.Some({ $0 + 3 }) <*> Optional.Some(2)
// => 5