haskell: creating list of records

537 views Asked by At

How to create a list of records in haskell

I have a Record

data TestList = Temp1 (String,[String])
          | Temp2 (String,[(String,String)])
    deriving (Show, Eq)

I am creating a list of records

testLists :: [TestList]
testLists =  [minBound..maxBound]

When I run, it throws me an error.

No instance for (Enum TestList)
      arising from the arithmetic sequence `minBound .. maxBound'
    Possible fix: add an instance declaration for (Enum TestList)
    In the expression: [minBound .. maxBound]
    In an equation for `testLists': testLists = [minBound .. maxBound]

It gives me a possible fix but I don't understand what it means. can anyone explain it and tell me how to fix it.

3

There are 3 answers

4
Fred Foo On BEST ANSWER

You can't use minBound and maxBound unless you declare beforehand what they mean for your type (which by the way is not a record type). You must, as the error also tells you, declare the type as an instance of Bounded. Without knowledge of what your type is to represent, it's impossible to say what such a declaration should look like exactly, but its general form is

instance Bounded TestList where
  minBound = ...
  maxBound = ...

(Fill in the ...)

0
John L On

There are two problems here. First, you'll need to create an Enum instance (as others have said). An Enum instance is required because you've used the special enumeration syntax [ a .. b].

Once you've created the Enum instance, you'll also need to write an instance for Bounded because you've used minBound and maxBound.

Usually you can tell Haskell compilers to derive both of these instances, however that won't work here because neither Lists nor Strings have instances for either type class. What value should maxBound :: String have, anyway? You could always make a longer string, or add another element to a list. Since you can't derive the instances, you'll have to manually write the Enum instance as in larsmans answer and similarly a Bounded instance.

0
Zach On

You didn't tell it how to enumerate values of type TestList. Even if it understands what minBound and maxBound are, it doesn't know how to discover what all of the values in between are (in order to create a list with those values).

By adding an instance declaration for Enum TestList, you would basically be instructing it on how to enumerate values, so it would be able to construct that sequence for you.