Skip to content

Instantly share code, notes, and snippets.

@Ben-G
Created June 4, 2015 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ben-G/542982cc102aaa1a4d4b to your computer and use it in GitHub Desktop.
Save Ben-G/542982cc102aaa1a4d4b to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import Foundation
/*
Basic Monad according to definition in: http://stackoverflow.com/questions/27750046/is-a-collection-with-flatmap-a-monad
The requirements for being a monad
- A monad has to be a type constructor F[_] that takes one type argument. For example, F could be List, Function0, Option, etc.
- A monadic unit. This is a function that takes a value of any type A and produces a value of type F[A].
- A monadic composition operation. It's an operation that takes a function of type A => F[B], and a function of type B => F[C] and produces a composite function of type A => F[C].
*/
struct A<T> {
var content: T
}
func monadicUnit<T>(p:T) -> A<T> {
return A(content: p)
}
func monadicComposition<T, U, V>(t1: T -> A<U>, t2: U -> A<V>) -> T -> A<V> {
return { x in
t2(t1(x).content)
}
}
A(content: 3)
let z = monadicComposition({ (x:Int) -> A<Int> in A(content: x * 2)}, {(y:Int) -> A<Int> in A(content: y * 4)})
z(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment