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
infix operator <*> { associativity left }
func <*><T, U>(f: (T -> U)?, a: T?) -> U? {
return a.apply(f)
}
func <*><T, U>(f: [T -> U], a: [T]) -> [U] {
return a.apply(f)
}
Optional.Some({ $0 + 3 }) <*> Optional.Some(2)
// => 5
[ { $0 + 3 }, { $0 * 2 } ] <*> [1, 2, 3]
// => [ 4, 5, 6, 2, 4, 6 ]
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 '??'
curriedAddition <^> Optional(2) <*> Optional(3)
func curriedTimes(a: Int)(b: Int) -> Int {
return a * b
}
curriedTimes <^> Optional(5) <*> Optional(3)
infix operator >>- { associativity left }
func >>-<T, U>(a: T?, f: T -> U?) -> U? {
return a.flatMap(f)
}
func half(a: Int) -> Int? {
return a % 2 == 0 ? a / 2 : .None
}
Optional(3) >>- half
// .None
Optional(4) >>- half
// 2
Optional.None >>- half
// .None
// For Optional
func >>-<T, U>(a: T?, f: T -> U?) -> U?
// For Array
func >>-<T, U>(a: [T], f: T -> [U]) -> [U]