![](/img/trans.png)
[英]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.