I am being asked to make an haskell function that computes something like
1^2 + 2^2 + 3^2 ...
While开发者_开发知识库 I find it quite easy to implement with list comprehensions
sum [ k^2 | k <- [1..100]]
or maps
sum (map (\x -> x*x) [1..100])
I'm having some hard time getting how to achieve it with foldls.
If I am not wrong, one needs no less than 3 parameters in a recursive function to achieve a result with this:
- The current position (1... up to n)
- The current sum
- Where to stop
Even if I define this function, it will still return a tuple, not a number (like I need it to!).
Could anyone be kind enough to give me some clues on what I may be missing?
Thanks
If you look at the definition of sum
, it's just sum = foldl (+) 0
. So if you replace sum
with foldl (+) 0
in either of your solutions, you have a solution using foldl
.
You can also get rid of the need for list comprehensions or map
by using foldl
with a function that adds the square of its second argument to its first argument.
I'm not sure where your considerations about recursive functions figure into this. If you're using foldl
, you don't need to use recursion (except in so far that foldl
is implemented using recursion).
However, you are wrong that a recursive function would need three arguments: A recursive functions summing the squares of each element in a list, would most straight-forwardly implemented by taking a list and adding the head of the list to the result of calling the function on the list's tail. The base case being squareSum [] = 0
. This has nothing to with foldl
, though.
The "current position" (actually the next item in the list, just like in your map and list comprehension versions) and where to stop are implicit in the list being folded over. The current sum is the "accumulator" parameter of the fold. So, fill in the blank:
foldl (\runningSum nextNumber -> ____) 0 [1..100]
精彩评论