[Haskell-cafe] what do I have to do exactlry with this exercises

Richard A. O'Keefe ok at cs.otago.ac.nz
Mon Nov 2 00:49:23 UTC 2015


On 30/10/2015, at 7:20 pm, Roelof Wobben <r.wobben at home.nl> wrote:

> Hello,
> 
> Im self studing Haskell with the Craft o ffunctional programmimg of Hutton.
> 
> Now I see two exercises that I do not understand what is really the purpose here.
> 
> The two exercises are :
> 
> 4.21 Given a function f of type Integer -> Integer give a recursive definition of a
> function of type Integer -> Integer which on input n returns the maximum
> of the values f 0, f 1, ..., f n. You might find the max function defined in
> Section 3.4 useful.
> To test this function, add to your script a definition of some values of f thus:
> f 0 = 0
> f 1 = 44
> f 2 = 17
> f _ = 0
> and so on; then test your function at various values.

You are to write a function of type Integer -> Integer.
So it doesn't receive f as a parameter,
f is "given" by being visible.

g :: Integer -> Integer
g n = the maximum of [f 0, ..., f n]

In general you would have two ways to do this:

(1) Roll your own recursion:

    g 0 = the maximum of [f 0] = ???
    g n = the maximum of [f 0, ..., f (n-1), f n]
            = some combination of the maximum of [f 0 ... f (n-1)]
              and f n

    This is a simple 2-line recursion.

(2) Actually make the list [f 0, ..., f n]
    -- there are several ways to do that, a list comprehension
    is readable but `map' could be used --
    and find the maximum from the list (so you are looking for
    a built in function Ord t => [t] -> t)

    This is a one-liner, but it's not recursive (or rather, YOUR
    part of it is not recursive), so this alternative is ruled out.

The purpose here is to get you writing a simple recursion.

> 
> 4.22 Given a function f of type Integer -> Integer give a recursive definition of
> a function of type Integer -> Bool which on input n returns True if one or
> more of the values f 0, f 1, ..., f n is zero and False otherwise.

The purpose here is probably to get you to realise that
4.21 and 4.22 have essentially the same solution (or more
precisely, have solutions which are structurally the same).




More information about the Haskell-Cafe mailing list