ATuin

Functions are Applicative, Functors and Monads

Oct 13th, 2012
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.85 KB | None | 0 0
  1.   def functionAsFunctorAndAsApplicativeAndAsMonad = {
  2.     /* Functions are Functors also, so implement map */
  3.     val f = (_:Int) + 3
  4.     val g = (_:Int) * 2
  5.  
  6.     println((f ∘ g)(2)) // g(f(2))
  7.     println(g(f(2)))
  8.  
  9.     /* Functions are also Applicatives, son implement |@| */
  10.     val ff = (f |@| g) { _ + _ } // f(x) + g(x)
  11.     val fff = (g |@| f) { _ + _} // g(x) + f(x)
  12.     println(ff(2), fff(2))
  13.  
  14.     /* Functions are also Monads, keeps some value inside a context,
  15.      * whose value is know  when we apply that function to some.
  16.      * This is just a Reader Monad
  17.      */
  18.     val sumTwoFunctions:Int => Int = for {
  19.       a <- f
  20.       b <- g
  21.     } yield a+b // f(x) + g(x)
  22.  
  23.     // f(x) + g(x)
  24.     val sumTwoFunctions2 = f >>= (a => g >>= (b => (c:Int) => a + b))
  25.  
  26.     println(sumTwoFunctions(2))
  27.     println(sumTwoFunctions2(2))
  28.   }
Advertisement
Add Comment
Please, Sign In to add comment