问题
i want to do something like:
succ' :: (Bounded a, Eq a, Enum a) => a -> a
succ' n
| n == (maxBound :: a) = minBound :: a
| otherwise = succ n
but this does not work. how to solve this?
回答1:
You don't need the type annotations, and they're the source of the errors you're getting:
succ' :: (Bounded a, Eq a, Enum a) => a -> a
succ' n
| n == maxBound = minBound
| otherwise = succ n
(This works in Haskell 98 and Haskell 2010, so pretty much any compiler you've got lying around .)
Also, I indented the |
a little, because they can't line up with the start of the function; they're part of the definition of succ'
, not standalone code.
Here's some test data:
data Test = A | B | C
deriving (Bounded, Eq, Enum, Show)
test = map succ' [A .. C]
I got [B,C,A]
.
回答2:
Several possibilities, the Haskell2010 way,
succ' :: (Bounded a, Eq a, Enum a) => a -> a
succ' n
| n == maxBound = minBound
| otherwise = succ n
the types are determined from the use, the type of both, maxBound
and minBound
must be the type of the argument.
Or you can use the ScopedTypeVariables
extension, bring the type variable into scope so it can be used in local type signatures,
{-# LANGUAGE ScopedTypeVariables #-}
succ' :: forall a. (Bounded a, Eq a, Enum a) => a -> a
succ' n
| n == (maxBound :: a) = minBound :: a
| otherwise = succ n
but, as seen above, there's no need for that here.
A third possibility is to use asTypeOf :: a -> a -> a
,
succ' :: (Bounded a, Eq a, Enum a) => a -> a
succ' n
| n == (maxBound `asTypeOf` n) = minBound `asTypeOf` n
| otherwise = succ n
which, again, is not needed here, but can be useful in other situations.
来源:https://stackoverflow.com/questions/13387881/haskell-bound-values-in-generic-functions