私はこのチュートリアルに従おうとしています: http://blog.jakubarnold.cz/2014/08/06/lens-tutorial-stab-traversal-part-2.html
ghci にロードする次のコードを使用しています。
{-# LANGUAGE RankNTypes, ScopedTypeVariables #-}
import Control.Applicative
import Data.Functor.Identity
import Data.Traversable
-- Define Lens type.
type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t
type Lens' s a = Lens s s a a
-- Lens view function. Omitting other functions for brevity.
view :: Lens s t a b -> s -> a
view ln x = getConst $ ln Const x
-- Tutorial sample data types
data User = User String [Post] deriving Show
data Post = Post String deriving Show
-- Tutorial sample data
john = User "John" $ map (Post) ["abc","def","xyz"]
albert = User "Albert" $ map (Post) ["ghi","jkl","mno"]
users = [john, albert]
-- A lens
posts :: Lens' User [Post]
posts fn (User n ps) = fmap (\newPosts -> User n newPosts) $ fn ps
そこから、次のような単純なものが機能します。
view posts john
ただし、次のステップを実行しようとすると機能しません。
view (traverse.posts) users
私は得る:
Could not deduce (Applicative f) arising from a use of ‘traverse’
from the context (Functor f)
bound by a type expected by the context:
Functor f => ([Post] -> f [Post]) -> [User] -> f [User]
at <interactive>:58:1-27
Possible fix:
add (Applicative f) to the context of
a type expected by the context:
Functor f => ([Post] -> f [Post]) -> [User] -> f [User]
In the first argument of ‘(.)’, namely ‘traverse’
In the first argument of ‘view’, namely ‘(traverse . posts)’
In the expression: view (traverse . posts) users
Lens には Functor の型制約があり、traverse には Applicative として f により制約された型制約があることがわかります。これが正確に機能しないのはなぜですか? また、ブログのチュートリアルで機能することが示唆されているのはなぜですか?