[Haskell] logic problem
Robert Dockins
robdockins at fastmail.fm
Tue Oct 25 23:08:02 EDT 2005
On Tuesday 25 October 2005 08:36 pm, michael at schmong.org wrote:
> Hi,
> My name is Michael. I'm new to Haskell. I'm working through
> The Craft of Functional Programming by Simon Thompson.
> I'm having problems with a few exercises from chapter 4. I will
> present one per post.
>
> This one is from 4.9
> Given a function f of type Int -> Int give a recursive definition
> of a function of type Int -> Int which on input n returns the maximum
> values f 0, f 1, ... , f n
>
> I defined f as follows
> f 0 = 0
> f 1 = 44
> f 2 = 5
> f 9 = 8
Most likely your problem is that f is only defined for
input values 0, 1, 2 and 9. If you call f with any other
value, you will end up with an error.
> this works except when f n > n. In that case I get an "illegal
> instruction" error and hugs exits.
> I'm pretty sure this is a logic problem. Could someone point me
> in the right direction so I can think about this problem correctly.
> Here is my code
>
> maxOverf :: Int -> Int
> maxOverf m
>
> | f m > m = (f m)
> | otherwise = (maxOverf m-1)
Here you are calling f with successively decreasing values; that will
run into areas where f is undefined for any value of m other than 1 or 2.
> Any hints/help/flames welcome. Thanks
Try a total rather than a partial function for f. You can just add a
default clause to the end, like
f _ = 0
which will define f x to be 0 for all values of x except the ones already
mentioned.
More information about the Haskell
mailing list