banovski

String to decimal integer

Apr 12th, 2022 (edited)
860
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import Data.Char
  2.  
  3. -- stdi (string to decimal integer) takes a string of digits and turns
  4. -- it into a decimal integer, sort of like atoi in C.
  5. stdi :: [Char] -> Int
  6. -- The function turns a string into a list (stl), goes through the
  7. -- list multiplying its items by ten to a power of a decrementing
  8. -- value and accumulating the results (lti); it calculates the maximum
  9. -- power value (mpv) by calculating the length of the list and
  10. -- subtracting 1.
  11. stdi str = lti mpv stl
  12. -- mpv - maximum power value: e.g. numbers from 1000 to 9999 consist
  13. -- of 4 digits therefore the maximum power is 4 - 1 = 3
  14.   where mpv = length stl - 1
  15. -- stl - string to list: applies the function digitToInt to every
  16. -- character in string and returns a list of integers.
  17.         stl = map digitToInt str
  18. -- lti goes through the list of integers multiplying them by
  19. -- ten to a power of a decrementing value and accumulating the results
  20.         lti _ [] = 0
  21.         lti n (x:xs) = x * 10 ^ n + lti (n - 1) xs
  22.  
  23. main :: IO ()
  24. main = print $ stdi "1000000" - 1
  25. -- 999999
Add Comment
Please, Sign In to add comment