我是否正确地得出结论,maxBound - minBound在Haskell中无法计算任意Enum和Bounded类型?或者我错过了一些技巧/黑客?这就是我所拥有的,显然无法运作:
difference :: (Enum a, Bounded a) => Int
difference = fromEnum maxBound - fromEnum minBound
Run Code Online (Sandbox Code Playgroud)
错误:
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
Run Code Online (Sandbox Code Playgroud)
我理解为什么我得到那个错误 - 那里没有类型的实际术语a,所以它无法弄清楚是什么a.问题是,是否有办法解决这个问题.
dav*_*420 12
difference :: (Enum a, Bounded a) => a -> Int
difference x = fromEnum (maxBound `asTypeOf` x)
- fromEnum (minBound `asTypeOf` x)
Run Code Online (Sandbox Code Playgroud)
称之为例如difference (undefined :: Char).
但请注意,对于某些类型(最值得注意的是Int),这会溢出,因此请使用Integer结果:
difference :: (Enum a, Bounded a) => a -> Integer
difference x = toEnum (fromEnum (maxBound `asTypeOf` x))
- toEnum (fromEnum (minBound `asTypeOf` x))
Run Code Online (Sandbox Code Playgroud)
使用a Proxy指定所需的类型,并使用ScopedTypeVariables该类型将其置于函数定义的范围内.
{-# LANGUAGE ScopedTypeVariables #-}
data Proxy a = Proxy
difference :: forall a . (Enum a, Bounded a) => Proxy a -> Int
difference Proxy = fromEnum (maxBound :: a) - fromEnum (minBound :: a)
>>> difference (Proxy :: Proxy Bool)
1
Run Code Online (Sandbox Code Playgroud)
编辑:使用丹尼尔的建议:
data Proxy a = Proxy
difference :: (Enum a, Bounded a) => Proxy a -> Int
difference p = fromEnum (max' p) - fromEnum (min' p) where
max' :: (Bounded a) => Proxy a -> a
max' Proxy = maxBound
min' :: (Bounded a) => Proxy a -> a
min' Proxy = minBound
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
559 次 |
| 最近记录: |