Tobias Bernhardt
Tobias Bernhardt

Reputation: 133

Haskell - Coding 'maximum' without actually using the function [beginner]

Complete the following function definition:

    -- maxi x y returns the maximum of x and y

I'm supposed to complete this task without using the 'maximum' function in Haskell.

maxi :: Integer -> Integer -> Integer
maxi x y
 |x > y = x
 |y > x = y 

Then I don't understand how to proceed. How do I test if the code is valid? And does it look somewhat correct?

Upvotes: 2

Views: 80

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You can test the function by calling it (yourself or with a test library, like QuickCheck). We can for example store the source code in a file (named test.hs):

-- test.hs

maxi :: Integer -> Integer -> Integer
maxi x y
 |x > y = x
 |y > x = y 

Then we can for example start a GHC interactive session, by using the ghci command and load the file passing the file name as a parameter. We can then call it:

$ ghci test.hs
GHCi, version 8.0.2: http://www.haskell.org/ghc/  :? for help
[1 of 1] Compiling Main             ( test.hs, interpreted )
Ok, modules loaded: Main.
*Main> maxi 2 9
9
*Main> maxi 3 5
5
*Main> maxi 7 2
7 

Is it correct? no. There is a case here that is not covered: in case x and y are the same, then it will raise an error:

*Main> maxi 7 7
*** Exception: test.hs:(4,1)-(6,13): Non-exhaustive patterns in function maxi

We can fix it by using otherwise as last check, which will always be True (in fact it is an alias for True). You can see otherwise as an else:

-- test.hs

maxi :: Integer -> Integer -> Integer
maxi x y
 | x > y = x
 | otherwise = y 

Upvotes: 7

Related Questions