tl;dr - の定義によると、すべての s に対して機能しないためLens
、 aを a にtraverse
することはできません。Lens
traverse
Functor
あなたのタイプを見てみましょう:
λ :set -XRankNTypes
λ :m +Control.Applicative Data.Traversable
λ type Lens s a = Functor f => (a -> f a) -> s -> f s
λ :t traverse
traverse
:: (Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b)
この時点で、 は、ある意味で、私たちのタイプtraverse
よりも少し一般的であることがわかります。つまり、レンズが からのみ関数を取得できるところから関数を取得できます。Lens
a -> f b
a -> f a
その場合に限定しても問題ないので、
λ :t traverse :: (Traversable t, Applicative f) => (a -> f a) -> t a -> f (t a)
traverse :: (Traversable t, Applicative f) => (a -> f a) -> t a -> f (t a)
:: (Applicative f, Traversable t) => (a -> f a) -> t a -> f (t a)
これで、型変数を並べる唯一の方法なので、 if が である場合traverse
はLens
でなければならないことは明らかです。Lens (t a) a
それでは、試してみましょう。
λ :t traverse :: Lens (t a) a
<interactive>:1:1:
Could not deduce (Traversable t1) arising from a use of `traverse'
from the context (Functor f)
bound by the inferred type of
it :: Functor f => (a -> f a) -> t a -> f (t a)
at Top level
or from (Functor f1)
bound by an expression type signature:
Functor f1 => (a1 -> f1 a1) -> t1 a1 -> f1 (t1 a1)
at <interactive>:1:1-24
Possible fix:
add (Traversable t1) to the context of
an expression type signature:
Functor f1 => (a1 -> f1 a1) -> t1 a1 -> f1 (t1 a1)
or the inferred type of
it :: Functor f => (a -> f a) -> t a -> f (t a)
In the expression: traverse :: Lens (t a) a
おっと、それは気に入らなかった。ちょっと待って、traverse
私たちの型を使用するためにt
は beTraversable
でなければならないので、その制限を追加しましょう。(「可能な修正」と同じように)提案:
λ :t traverse :: Traversable t => Lens (t a) a
<interactive>:1:1:
Could not deduce (Applicative f1) arising from a use of `traverse'
from the context (Functor f, Traversable t)
bound by the inferred type of
it :: (Functor f, Traversable t) => (a -> f a) -> t a -> f (t a)
at Top level
or from (Traversable t1, Functor f1)
bound by an expression type signature:
(Traversable t1, Functor f1) =>
(a1 -> f1 a1) -> t1 a1 -> f1 (t1 a1)
at <interactive>:1:1-41
Possible fix:
add (Applicative f1) to the context of
an expression type signature:
(Traversable t1, Functor f1) =>
(a1 -> f1 a1) -> t1 a1 -> f1 (t1 a1)
or the inferred type of
it :: (Functor f, Traversable t) => (a -> f a) -> t a -> f (t a)
In the expression: traverse :: Traversable t => Lens (t a) a
さて、ここでの問題は、それが (の定義から得られる) であると推測できないことf
ですApplicative
(これも を使用する必要があります)。traverse
Functor
Lens
Applicative f
ただし、コンテキストに追加することはできません-f
は隠されています。と言うとき、 はすべての sに対して機能する必要type Lens s a = Functor f => (a -> f a) -> s -> f s
があると言っています。Lens
Functor
しかしtraverse
、 である のサブセットに対してのみ機能しFunctor
ますApplicative
。したがって、このようにのタイプは、 esで許可されてtraverse
いるよりも具体的です。Lens