我正在尝试为以下数据结构创建镜头。我正在使用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
应该是一个遍历,而不是一个镜头。