3

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

4

1 回答 1

3

view实际上具有比 . 限制更少的类型Lens s t a b -> s -> a

如果你放弃类型签名,ghci 会告诉你类型view

:t view
view :: ((a1 -> Const a1 b1) -> t -> Const a b) -> t -> a

这限制较少,因为 aLens必须定义forall函子,而 view 的第一个参数只需要为 定义Const a1

如果我们根据名称重命名类型变量Lens并限制a1 ~ a此签名将更有意义

type Lens s t a b = forall f. Functor f =>
         (a -> f       b) -> s -> f       t 
view :: ((a -> Const a b) -> s -> Const a t) -> s -> a
view ln x = getConst $ ln Const x
于 2014-12-10T23:36:12.293 回答