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

  1. Print [minBound .. maxBound] for Bool and for a type of four constructors of your own.
  2. Write previousLevel :: Level -> Maybe Level with the same guard as nextLevel.
  3. Use fromEnum to print the position of every constructor of Level.
  4. Call succ High and read the run-time error.
  5. Write levelFromInt :: Int -> Maybe Level using toEnum and a bounds check.
  6. 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.

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

  2. What does fromEnum Blue return when Blue is the third constructor?

    Answer

    2

    Derived Enum counts from zero, so the third constructor is 2.

  3. What does toEnum 1 :: Color return for Red | Green | Blue?

    Answer

    Green

    Zero is Red, so one is Green.

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

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

  6. What does nextLevel High return in the lesson program?

    Answer

    Nothing

    The guard compares with maxBound and returns Nothing at the last value.

  7. Why is nextLevel total while succ is 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.

  8. Which two methods does Bounded have?

    Answer

    minBound and maxBound

    Bounded is the class of types with a smallest and a largest value.

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

  10. What is the risk of toEnum n on 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