Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Free Monads in Swift
//
// 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
You can’t perform that action at this time.