我正在尝试遵循本教程: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 具有更受约束的类型约束。为什么这不起作用,为什么博客教程建议它起作用?