How to use >=> in Scala?

旧街凉风 提交于 2019-12-05 02:23:41

There are two problems here. The first is that the inferred types of your functions are too specific. Option is a monad, but Some is not. In languages like Haskell the equivalent of Some isn't even a type—it's just a constructor—but because of the way algebraic data types are encoded in Scala you have to watch out for this issue. There are two easy fixes—either provide the more general type explicitly:

scala> val f: Int => Option[Int] = i => Some(i + 1)
f: Int => Option[Int] = <function1>

scala> val g: Int => Option[String] = i => Some(i.toString)
g: Int => Option[String] = <function1>

Or use Scalaz's handy some, which returns an appropriately typed Some:

scala> val f = (i: Int) => some(i + 1)
f: Int => Option[Int] = <function1>

scala> val g = (i: Int) => some(i.toString)
g: Int => Option[String] = <function1>

The second problem is that >=> isn't provided for plain old monadic functions in Scalaz—you need to use the Kleisli wrapper:

scala> val h = Kleisli(f) >=> Kleisli(g)
h: scalaz.Kleisli[Option,Int,String] = Kleisli(<function1>)

This does exactly what you want—just use h.run to unwrap.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!