gpt4 book ai didi

haskell - 可遍历数据常量 a b = 常量 a 通过快速检查,但表现得很有趣

转载 作者:行者123 更新时间:2023-12-01 11:25:36 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com