Skip to content

Instantly share code, notes, and snippets.

@Pitometsu
Last active May 13, 2020 03:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pitometsu/52fe469376c1bc43db69 to your computer and use it in GitHub Desktop.
Save Pitometsu/52fe469376c1bc43db69 to your computer and use it in GitHub Desktop.
Applicative functor in swift for (->)r type
// lets define Applicative Functor for (->)r type (function of function)
// tip: similar to Reader monad.
infix operator <*> { associativity left precedence 150 }
func <*> <A, B, C> (f : A -> B -> C, g : A -> B)(x : A) -> C {
return f (x) (g(x))
}
infix operator <|> { associativity left precedence 150 }
func <|> <A, B, C> (f : A -> B -> C, g : C -> A) -> C -> B -> C {
return pure(f) <*> g
}
func pure <T, A> (x : A) -> (T -> A) {
return { _ in x }
}
// end of functor functions
// curring
func curry <A, B, C> (f : (A, B) -> C) -> A -> B -> C {
return { a in { b in f(a, b) } }
}
// local functions
let add_3 = curry(+)(3)
let mul_100 = curry(*)(100)
let sum : Int -> Int -> Int = curry(+)
// let us play a little
let sum_add_mul = sum <|> add_3 <*> mul_100
println(sum_add_mul(x:5)) // => 508
func eval <T, U>(lhs: T, rhs: T -> U) -> U {
return rhs(lhs)
}
func call <T, U>(lhs: T -> U, rhs: T) -> U {
return lhs(rhs)
}
func |> <T, U>(lhs: T, rhs: T -> U) -> U {
return rhs(lhs);
}
infix operator |> { associativity left }
func <| <T, U>(lhs: T -> U, rhs: T) -> U {
return lhs(rhs);
}
infix operator <| { associativity right }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment