Reputation: 36404
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
sum' :: (Integral a) => [a] -> a
sum' [] = 0
sum' [a] = foldr (+) 0 ([a])
main = do putStrLn "Enter a number:"
num <- readLn
sum' (take num fibs)
That's my code to take the sum of a recursively produced list.
I could have done the foldr
operation at take num fibs
, but I wanted more control over the list and wanted a way in which I could take the sum of particular elements of a list rather than the whole list.
Where am I going wrong?
Upvotes: 1
Views: 176
Reputation: 17136
Your sum'
function is incorrect:
sum' [a] = foldr (+) 0 ([a])
This will only accept, and sum, a list of 1 element. :-)
Change it to:
sum' a = foldr (+) 0 a
And it will work.
You can also delete the redundant sum' [] = 0
line, and extend the type to sum' :: (Num a) => [a] -> a
.
Upvotes: 5