Enum and Bounded
Enum and the range syntax
The range syntax of the lesson on ranges is the Enum class in disguise: [a .. b] becomes enumFromTo a b, and a type needs an Enum instance to be used with it. Deriving Enum for a type with no fields numbers the constructors from zero in declaration order, which is also what toEnum and fromEnum expose.
module Main (main) where
data Color = Red | Green | Blue
deriving (Show, Enum, Bounded)
main :: IO ()
main = do
print ([minBound .. maxBound] :: [Color])
print (succ Red)
print (pred Blue)
print (toEnum 1 :: Color)
print (fromEnum Blue :: Int)
ghc -Wall -O1 -o enum enum.hs
./enum
[Red,Green,Blue]
Green
Green
Green
2
The first line is the whole list of values, written without naming them: minBound .. maxBound works for any type with both instances, and it is the idiom for "every case" in a menu, a parser or a test. The last line is the position of Blue in the declaration, counted from zero.
Bounded and minBound
Bounded has two methods, minBound and maxBound, and a derived instance takes the first and last constructors. For a type with fields the derived Bounded is only available if every field is bounded, and then the bounds are the combination of the field bounds; for a record it is usually not what a program means, which is why hand-written instances are common for numeric types.
print (minBound :: Int) -- -9223372036854775808
print (maxBound :: Int) -- 9223372036854775807
print (minBound :: Bool) -- False
print (maxBound :: Char) -- '\1114111'
Those four are the Prelude instances, and they show the two flavours: a numeric range with a real limit, and an enumeration with a first and a last element. The Char one prints an escape, because the last code point has no glyph.
A type that is both
With Enum and Bounded a function can ask for the next value without a partial succ, which is the pattern every menu or wizard needs:
module Main (main) where
data Level = Low | Medium | High
deriving (Show, Eq, Enum, Bounded)
allLevels :: [Level]
allLevels = [minBound .. maxBound]
nextLevel :: Level -> Maybe Level
nextLevel level
| level == maxBound = Nothing
| otherwise = Just (succ level)
main :: IO ()
main = do
print allLevels
print (nextLevel Low)
print (nextLevel High)
ghc -Wall -O1 -o bounded bounded.hs
./bounded
[Low,Medium,High]
Just Medium
Nothing
The guard is what makes the function total: at the last constructor there is no next value, and Maybe says so instead of crashing. succ High on its own would throw at run time, which is the next section.
succ and pred at the edge
succ and pred are partial: on maxBound and minBound there is no next or previous value, and the program dies with Prelude.succ: bad argument. The compiler does not warn about it, because the type of succ promises a value for every input of an Enum type; only the class law that guarantees it is missing.
succ (maxBound :: Int) -- throws: bad argument
pred (minBound :: Int) -- throws: bad argument
succ High -- throws, there is no constructor after High
The total replacement is the Maybe-returning function above, or enumFromTo when the whole range is wanted. The same care applies to toEnum: a number outside the range throws, while the range syntax never produces one. A program that reads a number from outside should use a bounds check and return Maybe or Either, as the lessons on Maybe and Either showed.
Exercises
- Print [minBound .. maxBound] for Bool and for a type of four constructors of your own.
- Write previousLevel :: Level -> Maybe Level with the same guard as nextLevel.
- Use fromEnum to print the position of every constructor of Level.
- Call succ High and read the run-time error.
- Write levelFromInt :: Int -> Maybe Level using toEnum and a bounds check.
- Explain why [minBound .. maxBound] is a better idiom than listing the constructors by hand.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the range
[minBound .. maxBound]produce for a derived Enum and Bounded type?Answer
Every constructor of the type, in declaration order
Enum numbers the constructors and Bounded gives the ends, so the range lists all of them.
-
What does
fromEnum Bluereturn when Blue is the third constructor?Answer
2
Derived Enum counts from zero, so the third constructor is 2.
-
What does
toEnum 1 :: Colorreturn for Red | Green | Blue?Answer
Green
Zero is Red, so one is Green.
-
What happens with
succ (maxBound :: Int)?Answer
It throws a bad argument error at run time
succ is partial and has no answer past the last value, and the type does not say so.
-
What does this program print?
module Main (main) where data Level = Low | Medium | High deriving (Show, Eq, Enum, Bounded) main :: IO () main = print ([minBound .. maxBound] :: [Level])Answer
[Low,Medium,High]
The range walks the constructors in declaration order.
-
What does
nextLevel Highreturn in the lesson program?Answer
Nothing
The guard compares with maxBound and returns Nothing at the last value.
-
Why is
nextLeveltotal whilesuccis not?Answer
It handles the edge case and returns Maybe instead of failing
The maxBound guard removes the failing input, and Nothing models the absence of a next value.
-
Which two methods does Bounded have?
Answer
minBoundandmaxBoundBounded is the class of types with a smallest and a largest value.
-
What does this program print?
module Main (main) where main :: IO () main = print (fromEnum (Just 3 < Just 4) :: Int)Answer
1
The comparison is True, and fromEnum of True is 1.
-
What is the risk of
toEnum non a number from outside?Answer
It throws when n is outside the type, so the input needs a check
toEnum is partial beyond the range, unlike a range expression that stops at the bound.
The code on this page was built with GHC 9.10.3 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev