教程中的简单 haskell 镜头违反了镜头法则
Simple haskell lens from tutorial violates lens law
我正在阅读本教程:
http://blog.jakubarnold.cz/2014/08/06/lens-tutorial-stab-traversal-part-2.html
我的代码如下所示:
import Control.Applicative
import Data.Traversable
import Control.Lens
data User = User String [Post] deriving Show
data Post = Post String deriving Show
posts :: Lens' User [Post]
posts f (User n p) = fmap (User n) (f p)
users :: [User]
users = [User "john" [Post "hello", Post "world"], User "bob" [Post "foobar"]]
tp :: (Traversable t, Applicative f) => ([Post] -> f [Post]) -> t User -> f (t User)
tp = traverse . posts
现在关注博客post,这里有一些常见的镜头计算:
*Main> view tp users
[Post "hello",Post "world",Post "foobar"]
*Main> set tp [Post "x",Post "y"] users
[User "john" [Post "x",Post "y"],User "bob" [Post "x",Post "y"]]
*Main> view tp (set tp [Post "x",Post "y"] users)
[Post "x",Post "y",Post "x",Post "y"]
最后的评价看得我一头雾水。下面的镜头法则不应该成立吗?
view l (set l v s) = v
这是一个镜头定律,tp
是一个遍历,所以不必遵守这个定律。
严格来说,view
根本不应该与遍历一起使用(无论如何它都可以工作,但它通过单向组合收集的结果来实现)。
我正在阅读本教程:
http://blog.jakubarnold.cz/2014/08/06/lens-tutorial-stab-traversal-part-2.html
我的代码如下所示:
import Control.Applicative
import Data.Traversable
import Control.Lens
data User = User String [Post] deriving Show
data Post = Post String deriving Show
posts :: Lens' User [Post]
posts f (User n p) = fmap (User n) (f p)
users :: [User]
users = [User "john" [Post "hello", Post "world"], User "bob" [Post "foobar"]]
tp :: (Traversable t, Applicative f) => ([Post] -> f [Post]) -> t User -> f (t User)
tp = traverse . posts
现在关注博客post,这里有一些常见的镜头计算:
*Main> view tp users
[Post "hello",Post "world",Post "foobar"]
*Main> set tp [Post "x",Post "y"] users
[User "john" [Post "x",Post "y"],User "bob" [Post "x",Post "y"]]
*Main> view tp (set tp [Post "x",Post "y"] users)
[Post "x",Post "y",Post "x",Post "y"]
最后的评价看得我一头雾水。下面的镜头法则不应该成立吗?
view l (set l v s) = v
这是一个镜头定律,tp
是一个遍历,所以不必遵守这个定律。
严格来说,view
根本不应该与遍历一起使用(无论如何它都可以工作,但它通过单向组合收集的结果来实现)。