1
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?

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

8 Comments

That doesn't really solve my purpose. As in, I get the total sum always. And not the sum of two elements of a particular position. Hence the confusion.
@Hick I see. Could you be more specific? What do you mean by "two elements of a particular position"? For the fibonacci sequence, the sum of two consecutive elements is represented by the next, so fibs!!5 will be the sum of elements 3 and 4.
Exactly. hence when I do a (take num fibs) !! num here, it crops up an error as the initial list of numbers is always greater than the list that is being computed, recursively.
What did you want to come out of (take num fibs) !! num?
so say I assign num as 200, the (take num fibs) !! num should give me the sum of 199 and 198th element. Else I've completely understood it wrong.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.