带有遍历的Haskell镜头教程

时间:2014-12-10 23:05:43

标签: haskell lens lenses

我试图遵循本教程: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在f上有一个更受约束的类型约束作为Applicative。为什么这不起作用,为什么博客教程表明它有效?

1 个答案:

答案 0 :(得分:3)

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

如果删除类型签名,ghci会告诉您view

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

限制性较小,因为Lens必须定义forall个仿函数,而第一个要查看的参数只需要为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