Ad
Algorithms
Strings

Haskell version of this kata: https://www.codewars.com/kata/5324945e2ece5e1f32000370

Translation

My Haskell translation is still messy but passing all the tests. When you have suggestions for a better one please share. It is my goal to translate this kata to hasekll.

Original Description

Given the string representations of two integers, return the string representation of the sum of those integers.

For example:

sumStrings('1','2') // => '3'

A string representation of an integer will contain no characters besides the ten numerals "0" to "9".

I have removed the use of BigInteger and BigDecimal in java

Python: your solution need to work with huge numbers (about a milion digits), converting to int will not work.

module Example where

{-zip the two numbers together into an array of tuples-}
parse :: String -> String -> [(Int, Int)]
parse s1 s2 = [(read [a] :: Int
                      , read [b] :: Int) | (a, b) <- if length s1 > length s2 
                                                     then zip (reverse s1) (reverse s2 ++ cycle "0") 
                                                     else zip (reverse s2) (reverse s1 ++ cycle "0")]

-- variable information:
-- o -> overhead
-- n, ns -> number, number rest

{-custom fold function-}
calc :: [(Int, Int)] -> String
calc =  recur "" 0 -- start the recursion
  where recur "" _ []         = "0" -- default case
        recur (n:ns) o []     = show ((read [n] :: Int) + o) ++ ns -- final solution
        recur ns o ((a,b):xs) = let r = o + a + b
                                in if r > 9  -- check for overflow
                                   then if null xs -- when this is the last number
                                        then show r ++ ns
                                        else recur (show (r - 10) ++ ns) (floorToNextLowestTen r) xs -- overflow call
                                   else recur (show r ++ ns) 0 xs -- normal call

{-solution wrapper-}
sumStr :: String -> String -> String
sumStr s1 s2 = calc $ parse s1 s2

{-helper funcs-}
floorToNextLowestTen :: Int -> Int
floorToNextLowestTen n = n `div` 10