Created
September 20, 2014 19:20
-
-
Save CodaFi/e340b90d71e2bfbafb99 to your computer and use it in GitHub Desktop.
Free Monads in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Free.swift | |
// Swift_Extras | |
// | |
// Created by Robert Widmann on 9/19/14. | |
// Copyright (c) 2014 Robert Widmann. All rights reserved. | |
// | |
import Foundation | |
public enum Free<F : Functor, A> { | |
case Pure(A) | |
case Roll(K1<Free<F, A>>) | |
} | |
extension Free : Functor { | |
typealias B = Any | |
typealias FA = Free<F, A> | |
typealias FB = Free<F, B> | |
public static func fmap<B>(f : A -> B) -> Free<F, A> -> Free<F, B> { | |
return { (let ftor) in | |
switch ftor { | |
case .Pure(let a): | |
return .Pure(f(a)) | |
case .Roll(let y): | |
return .Roll(Free.fmap({ F.fmap(f)($0) })(y)) | |
} | |
} | |
} | |
} | |
public func <%><F : Functor, A, B>(f: A -> B, io : Free<F, A>) -> Free<F, B> { | |
return Free.fmap(f)(io) | |
} | |
public func <^ <F : Functor, A, B>(x : A, io : Free<F, B>) -> Free<F, A> { | |
return Free.fmap(const(x))(io) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment