Sunday, 5 June 2016

Haskell: Convert String to Integer


StringUtil.hs
import Data.Char (digitToInt)

stringToInt :: [Char] -> Int
stringToInt [] = 0
stringToInt data1@(x:xs)
    | (x == '-') = (-1) * (getInt xs 0)
    | otherwise = getInt data1 0

getInt :: [Char] -> Int -> Int
getInt [] accumulator = accumulator
getInt (x:xs) accumulator = let 
                                acc = accumulator * 10 + (digitToInt x)
                            in
                                getInt xs acc

*Main> :load StringUtil.hs
[1 of 1] Compiling Main             ( StringUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> stringToInt "1234"
1234
*Main> stringToInt "-1234"
-1234



Previous                                                 Next                                                 Home

No comments:

Post a Comment