作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
haskell 书要我实现可遍历实例
newtype Constant a b = Constant { getConstant :: a }
包括所有必要的父类(super class)。下面的代码通过了 Quickcheck/Checkers
,但表现得很滑稽
import Test.QuickCheck
import Test.QuickCheck.Checkers
import Test.QuickCheck.Classes
newtype Constant a b = Constant { getConstant :: a }
instance Functor (Constant a) where
fmap f (Constant a) = Constant a
instance Foldable (Constant a) where
foldr f z (Constant x) = z
instance Traversable (Constant a) where
traverse f (Constant a) = pure $ Constant a
type TI = []
main = do
let trigger = undefined :: TI (Int, Int, [Int])
quickBatch (traversable trigger)
当我尝试像这样使用可遍历实例时:
traverse (\x -> [x + 1]) $ Constant 5
我没有得到我希望得到的Constant [5]
,而是
traverse (\x -> [x + 1]) $ Constant 5
:: (Num b, Num a) => [Constant a b]
这是什么意思?我做错了什么吗?
最佳答案
When I try to use the traversable instance like so:
traverse (\x -> [x + 1]) $ Constant 5
I do not get
Constant [5]
which I was hoping for [...]
您不会得到 Constant [5]
。让我们为 traverse
编写类型:
traverse :: (Traversable t, Applicative f) => (a -> f b) -> t a -> f (t b)
...并将其与您的实例化对齐:
-- I've substituted `x` for `a` and `y` for `b` in the
-- first type, because otherwise my head hurts.
(x -> f y) -> t x -> f (t y)
(Num a, Num b) => (a -> [] a) -> (Constant b) a -> [] ((Constant b) a)
所以我们有:
t = Constant b
f = []
x = Num a => a
y = NUm b => b
请注意,traverse
的类型意味着 t
在参数和结果中是相同的。由于您使用 Constant 5::Num a => Constant a b
作为参数,这意味着您永远不能拥有 Constant [5]::Num a => Constant [a] b
在结果中,因为 Constant a/= Constant [a]
。
关于haskell - 可遍历数据常量 a b = 常量 a 通过快速检查,但表现得很有趣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37468032/
我是一名优秀的程序员,十分优秀!