infix operator |> { associativity left } infix operator <| { associativity right } public func |> (a : A, f : A -> B) -> B { return f(a) } public func <| (f : A -> B, a : A) -> B { return f(a) }
func canCauseProblem(input: Int) -> ProblemHiding func possibleProblem(input: String) -> ProblemHiding func yetAnotherProblem(input: Double) -> ProblemHiding let input = 42 ProblemHiding(input) // udajemy że wszystko gra .execute(canCauseProblem) // jakby nic się nie stało .execute(possibleProblem) // bez nerwów, bez ifów .execute(yetAnotherProblem) // jak kwiat lotosu .obtainValue() // sprawdzam!
extension Optional : Monad { typealias A = Wrapped typealias B = Any // nil jest problemem typealias FB = B? func bind(f: A -> B?) -> B? { return self.flatMap(f) } } extension Array : Monad { typealias A = Element typealias B = Any // wiele wartości to problem typealias FB = Array func bind(f: A -> [B]) -> [B] { return self.flatMap(f) } }
enum Result { // możliwy ErrorType to problem case Success(Value) case Failure(ErrorType) } extension Result : Monad { typealias A = Value typealias B = Any typealias FB = Result func bind(f: A -> Result) -> Result { switch self { case .Success(let value): return f(value) case .Failure(let error): return .Failure(error) } } }