Colin Bernhardt
Colin Bernhardt

Reputation: 21

Type error in list comprehension

I am new to Haskell and I encountered a error like this.

learnHaskell.hs:1:51: error:
* No instance for (Enum [t0])
    arising from the arithmetic sequence `1 .. 10'
* In the expression: [1 .. 10]
  In a stmt of a list comprehension: radius <- [1 .. 10]
  In the expression:
    [(radius, area, circumference) |
       radius <- [1 .. 10],
       area <- 3.14 * radius ^ 2,
       circumference <- 3.14 * radius]

learnHaskell.hs:1:52: error:
* No instance for (Num [t0]) arising from the literal `1'
* In the expression: 1
  In the expression: [1 .. 10]
  In a stmt of a list comprehension: radius <- [1 .. 10]

learnHaskell.hs:1:67: error:
* No instance for (Fractional [t0]) arising from the literal `3.14'
* In the first argument of `(*)', namely `3.14'
  In the expression: 3.14 * radius ^ 2
  In a stmt of a list comprehension: area <- 3.14 * radius ^ 2

I am still new at this. Can someone help me figure out what's wrong. The source code is down below.

circles  = [(radius,area,circumference)|radius <- [1..10],area <- 3.14*radius^2,circumference<-3.14*radius ]

Upvotes: 1

Views: 106

Answers (1)

Adam Smith
Adam Smith

Reputation: 54163

Alec's comment explains the correct answer:

circles = [(radius, area, circumference) |
             radius <- [1..10],
             let area = 3.14 * radius ^ 2
                 circumference = 3.14 * radius]

Because ... <- ... is not the same as let ... = .... However it's helpful to understand the error message itself!

All three errors have lines like:

* No instance for (Enum [t0]) arising from the arithmetic sequence `1 .. 10'
* No instance for (Num [t0]) arising from the literal `1'
* No instance for (Fractional [t0]) arising from the literal `3.14

The second and third errors are the result of Haskell trying to iterate over your literal area and circumference definitions. That's what the left arrow does in a list comp. Both error messages are complaining that it can't find a way to turn the literal into a list, so it can't iterate from it.

Upvotes: 2

Related Questions