【发布时间】:2018-04-05 09:11:03
【问题描述】:
我有以下函数,它应该将给定列表中的所有数字加到当前位置。例如,subtotal [1, 2, 3, 4] = [1, 3, 6, 10],因为 1 = 1、1 + 2 = 3、1 + 2 + 3 = 6 和 1 + 2 + 3 + 4 = 10。
这是我的代码:
subtotal :: Num a => [a] -> [a]
subtotal [] = []
subtotal xs = [y | n <- [1..length xs], y <- sum(take n xs)]
问题是我得到这个错误:
cw.hs:3:46: error:
* Couldn't match expected type `[a]' with actual type `a'
`a' is a rigid type variable bound by
the type signature for:
subtotal :: forall a. Num a => [a] -> [a]
at cw.hs:1:1-31
* In the expression: sum (take n xs)
In a stmt of a list comprehension: y <- sum (take n xs)
In the expression:
[y | n <- [1 .. length xs], y <- sum (take n xs)]
* Relevant bindings include
xs :: [a] (bound at cw.hs:3:10)
subtotal :: [a] -> [a] (bound at cw.hs:2:1)
|
3 | subtotal xs = [y | n <- [1..length xs], y <- sum(take n xs)]
| ^^
我该如何解决?
【问题讨论】:
标签: list haskell types list-comprehension