我试图将我之前遇到的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/