gpt4 book ai didi

haskell - 获取有界类型的 minBound

转载 作者:行者123 更新时间:2023-12-02 10:49:55 25 4
gpt4 key购买 nike

我一直在尝试做这样的事情:

f :: (Enum a, Bounded a) => A a b -> [(a,b)]  
f x = [(as,bs) | as <- [minBound :: a ..] , bs <- x somefunction as]

但是那里的 minbound 似乎不起作用。我怎样才能得到它?

最佳答案

您需要启用 ScopedTypeVariables 扩展并使用显式 forall:

{-# ScopedTypeVariables #-}

f :: forall a b . (Enum a, Bounded a) => A a b -> [(a,b)]
f x = [(as,bs) | as <- [minBound :: a ..] , bs <- x somefunction as]

如果没有这个,在 Haskell 中,每个类型签名都会独立于其他类型签名进行解释。即minBound::a中的a与上面签名中的a无关。

如果你真的想坚持不使用扩展,你可以编写一个辅助函数:

myBound :: Bounded a => A a b -> a
myBound x = minBound -- does not really depend on x

f :: (Enum a, Bounded a) => A a b -> [(a,b)]
f x = [(as,bs) | as <- [myBound x ..] , bs <- x somefunction as]
<小时/>

在这种特定情况下,正如@dfeuer 在下面指出的那样,有一个更简单的解决方案。我们可以简单地删除 minBound 上的类型注释:

-- no extensions
f :: (Enum a, Bounded a) => A a b -> [(a,b)]
f x = [(as,bs) | as <- [minBound ..] , bs <- x somefunction as]

这是有效的,因为列表理解输出对 (as,bs),因此 Haskell 可以看到 as 必须具有类型 a,并且minBound 必须与 as 具有相同类型。

关于haskell - 获取有界类型的 minBound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29161825/

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