[Haskell-beginners] safe versions of pred and succ?

Graham Gill math.simplex at gmail.com
Sat Jan 14 07:35:17 UTC 2017


Suppose I have a function

f :: (Enum a) => a -> ...
f x ... = ...pred x ...

If a is also an instance of Bounded, then I get a runtime error if pred 
minBound is evaluated during evaluation of f.

If I try to protect the use of pred x with a check using minBound, then 
I have to add a Bounded constraint on type a, which would mean, for 
example, that I can no longer use f with type Integer.

Do I need two different versions of f, one for Bounded a and one for 
non-Bounded a? Is there a more elegant way to take care of this problem? 
I don't know much about all of the type magic available in GHC.

For example, from another list message,

groupConsecutive :: (Enum a,Eq a) => [a] -> [[a]]
groupConsecutive = foldr go []
     where go x ls@(hd@(y:_):yss)
             | x == y || x == pred y = (x:hd):yss
             | otherwise             = [x]:ls
           go x [] = [[x]]

 > groupConsecutive [1,2,3,7,8,10,11,12]
[[1,2,3],[7,8],[10,11,12]]

 > groupConsecutive ([1,0,1,2]::[Word])
*** Exception: Enum.pred{Word}: tried to take `pred' of minBound

In the first go case, if type a is also Bounded, y == minBound and x /= 
y, then we know already that x /= pred y, we want the guard to fail and 
that we pass to the otherwise guard to start a new sublist. But how to 
implement it without making the function unavailable for un-Bounded types?

Graham




More information about the Beginners mailing list