Reputation: 859
I try simply to iterate through a list and return each element.
iterateList [] = error "empty list"
iterateList [a] = a
iterateList (x:xs) = x iterateList xs
On the third line I try to return the first element and then recursively invoke iterateList
on the tail of the List.
But that's not working. Any idea why?
Example: input: iterateList [1,2,3,4,5] output: 1 2 3 4 5
Upvotes: 1
Views: 6998
Reputation: 85887
What I want is just par example a for loop in Java, where I can do something with each element in the list, like printing, sum, multiply, delete, just accessing those elements
Well, you can't "delete" anything in Haskell, and you can't modify bindings. What you can do is e.g. sum the elements:
sumList [] = 0
sumList (x : xs) = x + sumList xs
Or multiply the elements:
productList [] = 1
productList (x : xs) = x * productList xs
At this point you may realize that you've repeated yourself quite a bit, which is annoying. You can extract the common parts and turn the differences into parameters:
iterateList f z [] = z
iterateList f z (x : xs) = x `f` iterateList f z xs
sumList = iterateList (+) 0
productList = iterateList (*) 1
Here z
represents the "base value" to be returned for an empty input list, and f
is the "combine" function that tells it how to deal with the element and the rest of the list.
Printing is a bit more complex because you have to know how IO
works first (in particular, you should know about >>
and return
), but it can still be done:
doNothing = return ()
printAndThen x rest = print x >> rest
printList = iterateList printAndThen doNothing
... or using values directly instead of binding them to names first:
printList = iterateList (\x rest -> print x >> rest) (return ())
Finally you would realize that you've just reinvented foldr
. :-)
Upvotes: 4