Haskell: bound-values in generic functions

2019-08-05 06:15发布

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?

标签: haskell
2条回答
对你真心纯属浪费
2楼-- · 2019-08-05 06:34

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].

查看更多
太酷不给撩
3楼-- · 2019-08-05 06:49

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.

查看更多
登录 后发表回答