scala - 内部具有monoid和函数的元组的适用实例

标签 scala scalaz applicative monoids

我试图将我之前遇到的haskell示例转换为scalaz。原始示例是这样的:

("Answer to the ", (*)) <*> ("Ultimate Question of ", 6) <*> ("Life, the Universe, and Everything", 7)

据我所知,它使用this实例。

从字面上看,它不会转换为scalaz:
scala> ("Answer to the ", ((_: Int) * (_: Int)) curried) |@| ("Ultimate Question of ", 6) |@| ("Life, the Universe, and Everything", 7) tupled
res37: (java.lang.String, (Int => (Int => Int), Int, Int)) = (Answer to the Ultimate Question of Life, the Universe, and Everything,(<function1>,6,7))

虽然,我一直在寻找一个实例,而且它看起来像be there(据我所知,还是这样)。

所以,问题是:为什么它不这样工作?还是我错过/未正确得到什么?

最佳答案

Scalaz等效于Control.Applicative<*>的也称为<*>,尽管它以相反的顺序混淆了其参数。因此,以下工作原理:

val times = ((_: Int) * (_: Int)) curried
val a = "Answer to the "
val b = "Ultimate Question of "
val c = "Life, the Universe, and Everything"

(c, 7) <*> ((b, 6) <*> (a, times))

或者,正如我在回应您的评论时所指出的那样,如果您想坚持使用|@|,可以使用以下内容:
(a -> times |@| b -> 6 |@| c -> 7)(_ apply _ apply _)

我个人更喜欢<*>版本,即使它感到倒退。

我们可以更详细地了解正在发生的事情。首先,这里不需要Applicative的全部功能-Apply就可以了。我们可以使用Apply获取元组的implicitly实例:
scala> val ai = implicitly[Apply[({type λ[α]=(String, α)})#λ]]
ai: scalaz.Apply[[α](java.lang.String, α)] = scalaz.Applys$$anon$2@3863f03a

现在,我们可以将第一个元组应用于第二个元组:
scala> :t ai(a -> times, b -> 6)
(java.lang.String, Int => Int)

结果到第三位:
scala> :t ai(ai(a -> times, b -> 6), c -> 7)
(java.lang.String, Int)

我们想要的是:
scala> ai(ai(a -> times, b -> 6), c -> 7)._1
res0: java.lang.String = Answer to the Ultimate Question of Life, the Universe, and Everything

scala> ai(ai(a -> times, b -> 6), c -> 7)._2
res1: Int = 42
<*>上的MA方法将它包装得更好。

关于scala - 内部具有monoid和函数的元组的适用实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10937268/

相关文章:

java - 非宽松模式中的 SimpleDateFormat 在解析有效日期时抛出 ParseException

Scalaz 翻转嵌套的存在/验证 mono-whatevers-nads 围绕 pre-applicative-building

scala - akka Camel vs scalaz Camel

haskell - Haskell 中双序列和位遍历之间的关系如何运作?

scala - Monad 与 Future 的应用仿函数

java - 使用Java将Mat复制到OpenCV中的原始数组? (出现 "multiple of channels count"错误)

Scala:带有私有(private) setter 的公共(public) getter ?

Scala - "companion contains its own main method, which means no static forwarder can be generated"的含义

scala - 我可以使用 monad 转换器来简化这个组合吗?

haskell - "undoable"应用仿函数的例子?