Skip to content

Instantly share code, notes, and snippets.

@AhmedSoliman
Created April 26, 2015 15:33
Show Gist options
  • Save AhmedSoliman/44fcfd8b4b81a8140487 to your computer and use it in GitHub Desktop.
Save AhmedSoliman/44fcfd8b4b81a8140487 to your computer and use it in GitHub Desktop.
A sample quiz answer on how to create toString without relying on primitive toString method for integers
def customToString(x: Int): String = {
val digits: Array[Char] = Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
def recur(base: Int, digit: Int, accu: List[Char]): List[Char] = {
val newAcc = digits(digit) :: accu
if (base == 0) newAcc
else recur(base / 10, base % 10, newAcc)
}
val absX = math.abs(x)
val toCharList = recur(absX / 10, absX % 10, List.empty)
if (x < 0) ('-' :: toCharList).mkString
else toCharList.mkString
}
@ikhattab
Copy link

here's my solution in Haskell

toString :: Int -> String
toString n
  | i < 10 = [ ['0'..'9'] !! i ]
  | otherwise = sign ++ toString(i `div` 10) ++ toString(i `mod` 10)
  where i = abs n
        sign = if n < 0 then ['-'] else []

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment