gpt4 book ai didi

haskell - 是否无法计算 Enum 类型的 maxBound 和 minBound 之间的差异?

转载 作者:行者123 更新时间:2023-12-03 15:10:19 26 4
gpt4 key购买 nike

我是否可以得出无法计算 maxBound - minBound 的结论?在 Haskell 中获取任意 EnumBounded类型?还是我错过了一些技巧/黑客?这就是我所拥有的,这显然行不通:

difference :: (Enum a, Bounded a) => Int
difference = fromEnum maxBound - fromEnum minBound

错误:
Foo.hs:37:1:
Ambiguous constraint `Enum a'
At least one of the forall'd type variables mentioned by the constraint
must be reachable from the type after the '=>'
In the type signature for `difference': difference :: (Enum a, Bounded a) => Int

Foo.hs:37:1:
Ambiguous constraint `Bounded a'
At least one of the forall'd type variables mentioned by the constraint
must be reachable from the type after the '=>'
In the type signature for `difference': difference :: (Enum a, Bounded a) => Int

我明白为什么会出现这个错误——其中没有类型为 a 的实际术语。 ,所以它无法弄清楚 a 是什么是。问题是是否有办法解决这个问题。

最佳答案

difference :: (Enum a, Bounded a) => a -> Int
difference x = fromEnum (maxBound `asTypeOf` x)
- fromEnum (minBound `asTypeOf` x)

将其称为例如 difference (undefined :: Char) .

但请注意,这对于某些类型(最明显的是 Int )会溢出,因此请改用 Integer结果:
difference :: (Enum a, Bounded a) => a -> Integer
difference x = toEnum (fromEnum (maxBound `asTypeOf` x))
- toEnum (fromEnum (minBound `asTypeOf` x))

关于haskell - 是否无法计算 Enum 类型的 maxBound 和 minBound 之间的差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13240621/

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