[英]Haskell: Flaw in the description of applicative functor laws in the hackage Control.Applicative article?: it says Applicative determines Functor
[英]Applicative functor laws violation
从在线课程中锻炼。
假设,对于标准列表 Applicative functor, <*>
运算符以标准方式定义,而pure
更改为
pure x = [x,x]
会违反 Applicative typeclass 的哪些规律?
pure g <*> pure x ≡ pure (gx)
pure id <*> xs ≡ xs
fs <*> pure x ≡ pure ($ x) <*> fs
g <$> xs ≡ pure g <*> xs
(.) <$> us <*> vs <*> xs ≡ us <*> (vs <*> xs)
我创建了以下文件:
newtype MyList a = MyList {getMyList :: [a]}
deriving Show
instance Functor MyList where
fmap f (MyList xs) = MyList (map f xs)
instance Applicative MyList where
pure x = MyList [x,x]
MyList gs <*> MyList xs = MyList ([g x | g <- gs, x <- xs])
fs = MyList [\x -> 2*x, \x -> 3*x]
xs = MyList [1,2]
x = 1
g = (\x -> 2*x)
us = MyList [(\x -> 2*x)]
vs = MyList [(\x -> 3*x)]
然后我尝试:
同态: pure g <*> pure x ≡ pure (gx)
*Main> pure g <*> pure x :: MyList Integer
MyList {getMyList = [2,2,2,2]}
*Main> pure (g x) :: MyList Integer
MyList {getMyList = [2,2]}
身份: pure id <*> xs ≡ xs
*Main> pure id <*> xs :: MyList Integer
MyList {getMyList = [1,2,1,2]}
*Main> xs :: MyList Integer
MyList {getMyList = [1,2]}
交换: fs <*> pure x ≡ pure ($ x) <*> fs
*Main> fs <*> pure x
[2,3]
*Main> pure ($ x) <*> fs
[2,3]
Applicative-Functor: g <$> xs ≡ pure g <*> xs
*Main> g <$> xs
MyList {getMyList = [2,4]}
*Main> pure g <*> xs
MyList {getMyList = [2,4,2,4]}
组成: (.) <$> us <*> vs <*> xs ≡ us <*> (vs <*> xs)
*Main> (.) <$> us <*> vs <*> xs
MyList {getMyList = [6,12]}
*Main> us <*> (vs <*> xs)
MyList {getMyList = [6,12]}
不应违反组合,因为这里不使用pure
。
似乎同态、恒等和 Applicative-Functor 不起作用。 但是当我在课程中选择它们时,它说答案是错误的。 那么,谁是傻瓜:我还是课程的作者?
根据@DavidFletcher 的评论,使用您的代码,我看到交换测试的不同输出:
> fs <*> pure x
MyList {getMyList = [2,2,3,3]}
> pure ($ x) <*> fs
MyList {getMyList = [2,3,2,3]}
所以你可能想仔细检查那个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.