Sunday 5 June 2016

Haskell: Implement multiplication of numbers


Sample.hs
mul :: Integer -> Integer -> Integer
mul x y
    | (x == 0) || (y == 0) = 0
    | (x < 0) && (y < 0) = mul' (abs x) (abs y)
    | (x > 0) && (y > 0) = mul' x y
    | otherwise = negate (mul' (abs x) (abs y))

mul' :: Integer -> Integer -> Integer
mul' x y
    | (y == 0) = 0
    | otherwise = x + mul' x (y-1)

Prelude> :load Sample.hs
[1 of 1] Compiling Main             ( Sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> mul 10 20
200
*Main> mul 10 (-20)
-200
*Main> mul (-10) (-20)
200
*Main> mul 10 0
0
*Main> mul 0 10
0


Previous                                                 Next                                                 Home

No comments:

Post a Comment