Steve Frampton wrote:
>
> Hello:
>
> Suppose I have a function 'g' which either iteratively or recursively sums
> up results of calls to 'f'. I've predetermined that there will only ever
> be 20 things to sum up.
>
> I think the easiest solution would be iteration. However, I'm new to
> Haskell and it doesn't seem to have looping constructs?
>
> Therefore, perhaps the recursive approach would work. But unfortunately,
> I want to call my 'g' function without a parameter and get a result back
> -- but yet I'll need to pass a parameter to it in order for it to recurse.
> Catch 22.
>
> Any ideas?
I know a few people have given you some high-level ideas, but I get the
feeling that you may want something a little more concrete.
Straightforward:
> g :: Integer
> g = g' 20
> where
> g' 0 = f 0 -- or "g' 0 = 0" Depending on what you sum.
> g' i = (f i) + (g' (i - 1))
More efficient, using tail recursion:
> g :: Integer
> g = g' 20 0
> where
> g' 0 sum = sum + (f 0)
> g' i sum = g' (i - 1) (sum + (f i))
More "elegant". That is, shorter:
> g :: Integer
> g = sum (map f [0..20])
A perhaps more efficient version of the previous function.
> g :: Integer
> g = foldl (\sum i -> sum + (f i)) 0 [0..20]
Hopefully, that will give you a few ideas of the things you can do with
a functional language.
- Michael Hobbs