In scalaz there is a way to compose functions like a -> m b
and b -> m c
into a -> m c
(like the function here, from String
to Set[String]
). They are called Kleisli functions, by the way. In haskell this is done simply with >=>
on those functions. In scala you'll have to be a bit more verbose (by the way, I've changed the example a bit: I couldn't make it work with Set
, so I've used List
):
scala> import scalaz._, std.list._
import scalaz._
import std.list._
scala> def f(x: String) = List(x, x.reverse)
f: (x: String)List[String]
scala> def g(x: String) = List(x, x.toUpperCase)
g: (x: String)List[java.lang.String]
scala> val composition = Kleisli(f) >=> Kleisli(g)
composition: scalaz.Kleisli[List,String,java.lang.String] = scalaz.KleisliFunctions$$anon$18@37911406
scala> List("hi", "bye") flatMap composition
res17: List[java.lang.String] = List(hi, HI, ih, IH, bye, BYE, eyb, EYB)