2012-06-07 8 views
9

私は以前にスカラズにやって来たhaskellの例を変換しようとしていました。内部にモノイドと関数を持つタプルの適用インスタンス

("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に思えます。

ですから、問題は次のようなものです。なぜこのように動作しないのですか?それとも、私は見逃してしまったのですか?

+1

このコードは実際にはタプルの適用インスタンスにディスパッチします。これはリストのためにモノイド 'mappend'を使います(連結)。これはタプルの2番目のコンポーネントの関数の構成であり、最初の部分のリストの連結があります。 –

答えて

5

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を実行します。私たちは、implicitlyを使用してタプルのためApplyインスタンスを取得することができます。

scala> val ai = implicitly[Apply[({type λ[α]=(String, α)})#λ]] 
ai: scalaz.Apply[[α](java.lang.String, α)] = [email protected] 

は、今、私たちは、第二に私たちの最初のタプルを適用することができます。

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にちょうどいいです。

+0

ありがとうございます、それは想定されているように動作します。ちなみに、ApplicativeBuilderでこれを行う方法、それがもっと良く見えるかどうか、あなたは何か考えがありますか? – folone

+1

確かに、あなたは '(a - > times | @ | b - > 6 | @ | c - > 7)(_ apply _ apply _)'のようなことをすることができますが、 '<*>' –

+0

うん、これは動作します。私は事実に惑わされていました。「タップル」はモノイドを糊付けしていたので、それも機能を適用すると思いました。 – folone

関連する問題