Saturday, 4 June 2016

Haskell: Reverse digits and store them in list


revDigits.hs
toRevDigits :: Integer -> [Integer]
toRevDigits num
    |(num < 0) = toRevDigits ((-1) * num)
    |(num < 10) = [num]
    |otherwise = (getLastDigit num) : (toRevDigits (dropLastDigit num))

{- 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 revDigits.hs
[1 of 1] Compiling Main             ( revDigits.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> toRevDigits 123
[3,2,1]
*Main> 
*Main> toRevDigits (-123)
[3,2,1]
*Main> 
*Main> toRevDigits 1
[1]
*Main> 
*Main> toRevDigits 0
[0]
*Main> toRevDigits 32
[2,3]
*Main>



Previous                                                 Next                                                 Home

No comments:

Post a Comment