Implement Enum Instance behavior on custom data type in Haskell

Viewed 74

I've got a custom data type in Haskell to represent a traffic light

data TrafficLight = Red | Yellow | Green  

I'm attempting to implement the features of the Enum typeclass using an instance block like so:

instance Enum TrafficLight where
    succ Green = Yellow
    succ Yellow = Red
    succ Red = Green
    pred Green = Red
    pred Yellow = Green
    pred Red = Yellow

pred and succ work as expected, however I'd also like to implement the range function, such that I'd be able to call

ghci> [Green .. Red]

and have it return

[Green,Yellow,Red]

I understand that this functionality seems to come from the enumFrom function in the Enum typeclass, but I'm not completely sure how to implement it the say way I implemented pred and succ.

1 Answers

The description for enumFrom at haskell.org gives the following possible definition enumFrom n = n : enumFrom (succ n). It should work in your case.

Related