Created
January 31, 2015 05:02
-
-
Save Transfusion/2febd65384264b25291d to your computer and use it in GitHub Desktop.
showInt with fold, attempted tail recursion and normal recursion.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.List | |
showInt :: Integer -> String | |
showInt number = | |
let tostr = show number | |
in let digitcount = length tostr | |
in let b = zip tostr [digitcount, digitcount-1 ..1] | |
in foldr (\x y -> | |
if snd x `mod` 3 == 0 && snd x /= digitcount | |
then " "++[fst x]++y | |
else [fst x] ++ y) "" b | |
-- Attempted tail recursive implementation of insertSpaces. | |
showInt2 :: Integer -> String | |
showInt2 n = ys ++ (if null ys || null zs then "" else " ") ++ drop 1 (reverse(insertSpaces zs)) | |
where | |
xs = show n | |
(ys,zs) = splitAt (length xs `mod` 3) xs | |
insertSpaces str = insertSpaces2 str "" | |
insertSpaces2 :: String -> String -> String | |
insertSpaces2 [] append = append | |
insertSpaces2 (x:y:z:xs) append = | |
insertSpaces2 (xs) ( [z,y,x, ' '] ++ append ) | |
showInt3 :: Integer -> String | |
showInt3 n = ys ++ (if null ys || null zs then "" else " ") ++ insertSpaces3 zs | |
where | |
xs = show n | |
(ys,zs) = splitAt (length xs `mod` 3) xs | |
insertSpaces3 :: String -> String | |
insertSpaces3 (a:b:c:x:xs) = [a,b,c,' '] ++ insertSpaces3 (x:xs) | |
insertSpaces3 xs = xs | |
--main :: IO () | |
--main = do | |
-- putStrLn $ show (length (showInt $ product [1..80000]) ) | |
-- putStrLn $ show (length (showInt2 $ product [1..80000]) ) | |
-- putStrLn $ show (length (showInt3 $ product [1..80000]) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment