我想写一个安全的toEnum
版本:
safeToEnum :: (Enum t, Bounded t) => Int -> Maybe t
天真的实现:
safeToEnum :: (Enum t, Bounded t) => Int -> Maybe t
safeToEnum i =
if (i >= fromEnum (minBound :: t)) && (i <= fromEnum (maxBound :: t))
then Just . toEnum $ i
else Nothing
main = do
print $ (safeToEnum 1 :: Maybe Bool)
print $ (safeToEnum 2 :: Maybe Bool)
而且它不起作用:
safeToEnum.hs:3:21:
Could not deduce (Bounded t1) from the context ()
arising from a use of `minBound' at safeToEnum.hs:3:21-28
Possible fix:
add (Bounded t1) to the context of an expression type signature
In the first argument of `fromEnum', namely `(minBound :: t)'
In the second argument of `(>=)', namely `fromEnum (minBound :: t)'
In the first argument of `(&&)', namely
`(i >= fromEnum (minBound :: t))'
safeToEnum.hs:3:56:
Could not deduce (Bounded t1) from the context ()
arising from a use of `maxBound' at safeToEnum.hs:3:56-63
Possible fix:
add (Bounded t1) to the context of an expression type signature
In the first argument of `fromEnum', namely `(maxBound :: t)'
In the second argument of `(<=)', namely `fromEnum (maxBound :: t)'
In the second argument of `(&&)', namely
`(i <= fromEnum (maxBound :: t))'
就我所理解的消息而言,尽管有显式类型声明(
minBound
),但编译器无法识别maxBound
和safeToEnum
应产生与:: t
结果类型完全相同的类型。知道如何解决吗?解决了
camccann和Dave的解决方案都可以工作(尽管Dave的解决方案需要调整)。谢谢你们两个(但我只能接受一个)。 ScopedTypeVariables的工作示例:
{-# LANGUAGE ScopedTypeVariables #-}
safeToEnum :: forall t . (Enum t, Bounded t) => Int -> Maybe t
safeToEnum i =
if (i >= fromEnum (minBound :: t)) && (i <= fromEnum (maxBound :: t))
then Just . toEnum $ i
else Nothing
最佳答案
作用域类型变量在这里不是必需的,您只需要向GHC明确表示您希望所有Enum
东西都属于同一类型。通过将它们全部传递给一个显式采用相同类型的Enum
的函数,这很容易做到。这是一种方法:
enumIfBetween :: (Enum a) => a -> a -> Int -> Maybe a
enumIfBetween a z x = let a' = fromEnum a
z' = fromEnum z
in if a' <= x && x <= z'
then Just $ toEnum x
else Nothing
safeToEnum i = enumIfBetween minBound maxBound i
main = do
print $ (safeToEnum 1 :: Maybe Bool)
print $ (safeToEnum 2 :: Maybe Bool)
在GHCi中尝试:
> main
Just True
Nothing
使用相同原理的更通用的解决方案是标准库函数
asTypeOf
,该函数具有与const
相同的行为,但要求两个参数都具有相同的类型:safeToEnum :: (Enum t, Bounded t) => Int -> Maybe t
safeToEnum i = let r = toEnum i
max = maxBound `asTypeOf` r
min = minBound `asTypeOf` r
in if i >= fromEnum min && i <= fromEnum max
then Just r
else Nothing
此版本也适用。
请记住,
ScopedTypeVariables
是语言的扩展,因此不一定在编译器之间可移植。实际上,几乎每个人都使用GHC,但通常首选在可能的情况下坚持使用标准基本语言(即Haskell 98)。在这种情况下,ScopedTypeVariables
确实过大了;这种情况下的Haskell wiki suggests asTypeOf
as a portable replacement。