Skip to content

Instantly share code, notes, and snippets.

@jarsen
Created March 18, 2015 21:17
Show Gist options
  • Save jarsen/d0230bb7ade41c96e381 to your computer and use it in GitHub Desktop.
Save jarsen/d0230bb7ade41c96e381 to your computer and use it in GitHub Desktop.
Shows how you can use `bind` and `reduce` to short circuit a bunch of mapping
// Playground - noun: a place where people can play
import UIKit
public class Box<T> {
let unbox: T
init(_ value: T) {
unbox = value
}
}
public enum Result<T> {
case Success(Box<T>)
case Failure(String)
init(_ value:T) {
self = .Success(Box(value))
}
}
extension Result {
public func bind<U>(f: T -> Result<U>) -> Result<U> {
switch self {
case let .Success(value):
return f(value.unbox)
case let .Failure(error):
return .Failure(error)
}
}
public func fmap<U>(f: T->U) -> Result<U> {
switch self {
case let .Success(value):
return .Success(Box(f(value.unbox)))
case let .Failure(error):
return .Failure(error)
}
}
}
func isOdd(x: Int) -> Bool {
return x % 2 != 0
}
let numbers = Array(1..<10)
let oddNumbers = filter(numbers, isOdd)
func doubleOddNumber(x: Int) -> Result<Int> {
println("Trying \(x)")
if !isOdd(x) {
return .Failure("\(x) is not odd")
}
else {
return Result(x * 2)
}
}
let result = reduce(numbers, Result([Int]())) { acc, number in
acc.bind { (var array) in
return doubleOddNumber(number).bind { oddNumber in
array.append(oddNumber)
return Result(array)
}
}
}
switch result {
case let .Success(value):
let v = value.unbox
case let .Failure(message):
println(message)
}
let result2 = reduce(oddNumbers, Result([Int]())) { acc, number in
acc.bind { (var array) in
doubleOddNumber(number).bind { oddNumber in
array.append(oddNumber)
return Result(array)
}
}
}
switch result2 {
case let .Success(value):
let v = value.unbox
case let .Failure(message):
println(message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment