Haskell: bound-values in generic functions

这一生的挚爱 提交于 2019-12-24 10:15:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!