Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def functionAsFunctorAndAsApplicativeAndAsMonad = {
- /* Functions are Functors also, so implement map */
- val f = (_:Int) + 3
- val g = (_:Int) * 2
- println((f ∘ g)(2)) // g(f(2))
- println(g(f(2)))
- /* Functions are also Applicatives, son implement |@| */
- val ff = (f |@| g) { _ + _ } // f(x) + g(x)
- val fff = (g |@| f) { _ + _} // g(x) + f(x)
- println(ff(2), fff(2))
- /* Functions are also Monads, keeps some value inside a context,
- * whose value is know when we apply that function to some.
- * This is just a Reader Monad
- */
- val sumTwoFunctions:Int => Int = for {
- a <- f
- b <- g
- } yield a+b // f(x) + g(x)
- // f(x) + g(x)
- val sumTwoFunctions2 = f >>= (a => g >>= (b => (c:Int) => a + b))
- println(sumTwoFunctions(2))
- println(sumTwoFunctions2(2))
- }
Advertisement
Add Comment
Please, Sign In to add comment