4

我正在尝试为以下数据结构创建镜头。我正在使用lens-family.

data Tree = Tree {
        _text :: String,
        _subtrees :: [Tree]
    } deriving (Show,Eq,Read,Generic)

出于各种原因,我想避免使用 Template Haskell。一方面,它似乎不适用于我的 ghc 版本(7.8.3),这是另一个(超出范围)问题。

为唱片制作镜头并不难。

text :: Lens' Tree String
text f (Tree text' subtrees') =
  (\text'' -> Tree text'' subtrees') `fmap` (f text')

subtrees :: Lens' Tree [Tree]
subtrees f (Tree text' subtrees') =
  (\subtrees'' -> Tree text' subtrees'') `fmap` (f subtrees')

但似乎 lens-family 没有列表的默认镜头。我认为这是可能的。有为lens。这些是我失败的尝试:

import Lens.Family2
import Lens.Family2.Unchecked
-- List lenses
_last :: Lens [a] [a'] a a'
_last f l =
  -- first try
  --lens getter setter
  -- second try
  (\el -> (init l) ++ el) `fmap`(f (last l))
  where
    getter = last
    setter l el = l ++ el

他们都得到一个类似于这个的错误:

Could not deduce (a' ~ [a'])
    from the context (Functor f)
      bound by the type signature for
                 _last :: Functor f => LensLike f [a] [a'] a a'
      at editor.hs:22:10-27
      ‘a'’ is a rigid type variable bound by
           the type signature for
             _last :: Functor f => LensLike f [a] [a'] a a'
           at editor.hs:22:10
    Expected type: f [a']
      Actual type: f a'
    Relevant bindings include
      f :: a -> f a' (bound at editor.hs:23:7)
      _last :: LensLike f [a] [a'] a a' (bound at editor.hs:23:1)
    In the second argument of ‘fmap’, namely ‘(f (last l))’
    In the expression: (\ el -> (init l) ++ el) `fmap` (f (last l))

如何定义_last镜头?

编辑:这是一个构建的版本:

_last f l = (\el -> (init l) ++ [el]) `fmap`(f (last l))

虽然,正如大卫/丹尼尔指出的那样,_last应该是一个遍历,而不是一个镜头。

4

1 回答 1

6

el您在((++)为两个参数都列出了一个列表)周围缺少方括号。如果你把它们放进去,你的第一次尝试应该会奏效。你的类型也太笼统了。列表在 Haskell 中不是异构的,因此它们只能包含一种类型的值。

此外,正如丹尼尔瓦格纳所说,这不可能是一个真正的镜头,因为它是局部的。您链接到的镜头文档已过期。当前的镜头库有_lastasTraversal可以避免这个问题,因为 aTraversal可以有 0 个或更多目标,而镜头必须正好有 1 个。

于 2015-04-12T16:41:49.453 回答