如何使用 >=>在斯卡拉? [英] How to use >=> in Scala?

查看:54
本文介绍了如何使用 >=>在斯卡拉?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Scala 中使用 >=>(Kleisli 箭头).据我了解,它组合了返回 monad 的函数.现在我尝试如下:

<前>Scala> val f = {i:Int => Some(i + 1)}f: Int => Some[Int] = Scala> val g = {i:Int => Some(i.toString)}g: Int => Some[String] = Scala> val h = f >>> g<console>:15: 错误:值 >>=> 不是 Int => Some[Int] 的成员val h = f >>=> g^

为什么不编译?如何用 >=> 组合 fg ?

解决方案

这里有两个问题.首先是你的函数的推断类型太具体了.Option 是一个 monad,但 Some 不是.在像 Haskell 这样的语言中,Some 的等价物甚至不是一个类型——它只是一个构造函数——但是由于代数数据类型在 Scala 中的编码方式,你必须注意这个问题.有两个简单的修复方法——要么明确提供更通用的类型:

scala>val f: Int =>选项[Int] = i =>一些(i + 1)f: 整数 =>选项[Int] = <function1>标度>val g: Int =>选项[字符串] = i =>一些(i.toString)g:整数=>选项[字符串] = <function1>

或者使用Scalaz方便的some,它返回一个适当类型的Some:

scala>val f = (i: Int) =>一些(我+ 1)f: 整数 =>选项[Int] = <function1>标度>val g = (i: Int) =>一些(i.toString)g:整数=>选项[字符串] = <function1>

第二个问题是 >=> 没有为 Scalaz 中的普通老式 monadic 函数提供——你需要使用 Kleisli 包装器:

scala>val h = Kleisli(f) >=>克莱斯利(g)h: scalaz.Kleisli[Option,Int,String] = Kleisli()

这正是你想要的——只需使用 h.run 来解包.

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 >=> ?

解决方案

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.

这篇关于如何使用 &gt;=&gt;在斯卡拉?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆