Skip to content

Instantly share code, notes, and snippets.

@CodaFi
Created September 20, 2014 19:20
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CodaFi/e340b90d71e2bfbafb99 to your computer and use it in GitHub Desktop.
Save CodaFi/e340b90d71e2bfbafb99 to your computer and use it in GitHub Desktop.
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