Friday, 3 June 2016

Haskell: Drop last digit from a number


dropLastDigit.hs
{- Drop last digit -}
dropLastDigit :: Integer -> Integer
dropLastDigit num
    | (num < 0) = (-1) * (dropLastDigit ((-1) * num))
    | otherwise = processNum (num `div` 10) 0

{- Return the last digit of a number -}
getLastDigit :: Integer -> Integer
getLastDigit num
    | (num < 0) = ((-1) * num) `rem` 10
    | otherwise = num `rem` 10

processNum num temp
    | (num==0) = 0
    | otherwise = ((getLastDigit num) * (10 ^ temp)) + processNum (num `div` 10) (temp+1)

*Main> :load dropLastDigit.hs
[1 of 1] Compiling Main             ( dropLastDigit.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> dropLastDigit 51
5
*Main> 
*Main> dropLastDigit 5
0
*Main> 
*Main> dropLastDigit (-15)
-1
*Main> dropLastDigit (-15234)
-1523



Previous                                                 Next                                                 Home

No comments:

Post a Comment