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
func plusThree(addend: Int) -> Int {
return addend + 3
}
Optional.Some(2).map(plusThree)
// => .Some(5)
Optional.Some(2).map { $0 + 3 }
// => .Some(5)
func map<U>(f: T -> U) -> U? {
switch self {
case .Some(let x): return f(x)
case .None: return .None
}
Optional.None.map { $0 + 3 }
// => .None
let post = Post.findByID(1)
if post != nil {
return post.title
} else {
return nil
}
findPost(1).map(getPostTitle)
infix operator <^> { associativity left }
func <^><T, U>(f: T -> U, a: T?) -> U? {
return a.map(f)
}
getPostTitle <^> findPost(1)
map({ $0 + 2 }, { $0 + 3 })
// => ???
typealias IntFunction = Int -> Int
func map(f: IntFunction, _ g: IntFunction) -> IntFunction {
return { x in f(g(x)) }
}
let foo = map({ $0 + 2 }, { $0 + 3 })
foo(10)
// => 15
extension Optional {
func apply<U>(f: (T -> U)?) -> U? {
switch f {
case .Some(let someF): return self.map(someF)
case .None: return .None
}
}
}
extension Array {