Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Monads in Swift -
public final class Box<T>
{
let value : T
public init(_ value : T) {
self.value = value
}
}
func flatten<T>(box : Box<Box <T>>) -> Box <T> {
return box.value
}
func map<T,U>(box : Box<T>, f : T -> U) -> Box<U> {
return Box(f(box.value))
}
infix operator >>= {associativity left}
func >>= <T,U>(box : Box<T>, f : T -> Box<U>) -> Box<U> {
return flatten(map(box,f))
}
func constructor<T>(value: T)->Box<T> {
return Box(value)
}
let f = {Box($0 + 1)}
let a = 1
let x = Box(a) >>= f
let y = f(a)
let x1 = Box(1)
let y1 = Box(1) >>= constructor
let double = {Box(2 * $0)}
let triple = {Box(3 * $0)}
let x2 = Box(1) >>= double >>= triple
let y2 = Box(1) >>= {double($0) >>= triple}
let box = Box(4)
let sum3 = {Box($0 + 3)}
let toString = {Box(String($0 + 0))}
let iReallyLike = {Box("I really like the number " + $0)}
let luckyNumber7 = box >>= sum3 >>= toString >>= iReallyLike
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment