In Scala, one can define a functor something like this:
trait Functor[X] {
def map[Y](f: X => Y): Functor[Y]
}
All we need here is map.
List
s have map
, Option
s have map
... The natural use of a map
is to apply it to a function. Like this:
def loop[X,Y](f: Functor[X], a: X=>Y) = f.map(a)
In Scala, loops can work as maps. And if you are a Haskell programmer, you'll immediately recognize your monadic notation:
def loop[X,Y](f: Functor[X], a: X=>Y) = for (x <- f) yield a(x)
These two are exactly the same.
Praise Scala!
Update: see recent blog entry on monads by Luc Duponchel for a lot more details.
No comments:
Post a Comment