Skip to content

Instantly share code, notes, and snippets.

@debasishg
Created November 17, 2010 17:01
Show Gist options
  • Save debasishg/703647 to your computer and use it in GitHub Desktop.
Save debasishg/703647 to your computer and use it in GitHub Desktop.
Examples of Applicative Functors
// Option as functor which gets pimped by map defined in MA.scala
// map takes a pure function & lifts it within the functor
Some(10) map {x: Int => x * 2} should equal(Some(20))
// List as functor : works the same way as Option as functor
List(10, 20, 30, 40) map {x: Int => x * 2} should equal(List(20, 40, 60, 80))
// List as applicative
List(10, 20, 30) <*> (List(1, 2, 3) map ((_: Int) * (_: Int)).curried) should equal(List(10, 20, 30, 20, 40, 60, 30, 60, 90))
// filter (>50) $ (*) <$> [2,5,10] <*> [8,10,11] << from lyah
(List(8, 10, 11) <*> (List(2, 5, 10) map ((_: Int) * (_: Int)).curried)).filter(_ > 50) should equal(List(55, 80, 100, 110))
// lift 2 for List
List(10, 20, 30).<**>(List(1, 2, 3))(_ * _) should equal(List(10, 20, 30, 20, 40, 60, 30, 60, 90))
// applicatives on list and functions
// [(+),(*)] <*> [1,2] <*> [3,4] << from lyah
val a2 = ((_: Int) + (_: Int)).curried
val p2 = ((_: Int) * (_: Int)).curried
List(3, 4) <*> (List(1, 2) <*> List(a2, p2)) should equal(List(4, 5, 5, 6, 3, 4, 6, 8))
// (++) <$> ["ha","heh","hmm"] <*> ["?","!","."] << from lyah
val c2 = ((_ : String) ++ (_: String)).curried
List("?", "!", ".") <*> (List("ha", "heh", "hmm") map c2) should equal(List("ha?", "ha!", "ha.", "heh?", "heh!", "heh.", "hmm?", "hmm!", "hmm."))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment