在列表解析中键入错误

时间:2017-10-03 21:04:08

标签: haskell

我是Haskell的新手,我遇到了这样的错误。

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

我还是新手。有人可以帮我弄清楚是什么错。 源代码在下面。

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

1 个答案:

答案 0 :(得分:2)

Alec的评论解释了正确答案:

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

因为... <- ...let ... = ...不同。但是,理解错误消息本身很有帮助!

所有三个错误都有如下行:

* 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

第二个和第三个错误是Haskell试图迭代你的文字区域和周长定义的结果。那是左箭头在列表组件中的作用。这两条错误消息都抱怨它无法找到将文字转换为列表的方法,因此它无法从中进行迭代。