How to use >=> in Scala?

喜欢而已 提交于 2019-12-06 21:47:57

问题


I am trying to use >=> (Kleisli arrow) in Scala. As I understand, it composes functions returning monads. Now I am trying it as follows:

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

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

scala> val h = f >=> g
<console>:15: error: value >=> is not a member of Int => Some[Int]
       val h = f >=> g
                 ^

Why does not it compile ? How to compose f and g with >=> ?


回答1:


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.



来源:https://stackoverflow.com/questions/21660556/how-to-use-in-scala

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