[Haskell-cafe] General Advice Needed ..

Henk-Jan van Tuyl hjgtuyl at chello.nl
Thu Jan 14 11:01:56 EST 2010


On Thu, 14 Jan 2010 15:38:26 +0100, Ian675 <adam_khan_rfc at hotmail.com>  
wrote:

>
> Pretty much yeah.. Im going through the book and things like :
>
> Define a function rangeProduct which when given natural numbers m and n,
> returns the product m*(m+1)*....*(n-1)*n
>
> I got the solution from my lecture notes but I still dont understand it..
>
> rangeProduct :: Int -> Int -> Int
> rangeProduct m n
>                   | m > n = 0
>                   | m == n = m
>                   | otherwise = m * rangeProduct (m+1) n
>

I'll try to give a clear explanation of this function:

> rangeProduct :: Int -> Int -> Int
> rangeProduct m n
A function is defined with parameters m and n, both Int; the result of the  
function is also an Int

>                   | m > n = 0
If m > n, the result is 0; the rest of the function definition will be  
skipped

>                   | m == n = m
If m is not larger then n, evalution continues here; if m == n, the result  
of the function is m


>                   | otherwise = m * rangeProduct (m+1) n
If previous predicates were False, this branch is evaluated ("otherwise"  
is always True); the function calls itself with (m+1) as first parameter

The boolean expressions in this function are called "guards"; the right  
hand side after the first guard that evaluates to True, will give the  
result of the function.

Regards,
Henk-Jan van Tuyl


--
http://Van.Tuyl.eu/
http://members.chello.nl/hjgtuyl/tourdemonad.html
--


More information about the Haskell-Cafe mailing list