Last active
August 29, 2015 14:04
-
-
Save benolee/a50d24814c74d48b63d6 to your computer and use it in GitHub Desktop.
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
-- Exercise 1 | |
-- converts positive Integers to a list of digits. | |
toDigits :: Integer -> [Integer] | |
toDigits x = reverse (toDigitsRev x) | |
toDigitsRev :: Integer -> [Integer] | |
toDigitsRev x | |
| x <= 0 = [] | |
| otherwise = (mod x 10) : toDigitsRev (div x 10) |
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
-- Exercise 1 | |
import Data.List | |
import Data.Tuple | |
-- converts positive Integers to a list of digits. | |
toDigits :: Integer -> [Integer] | |
toDigits x = reverse (toDigitsRev x) | |
toDigitsRev :: Integer -> [Integer] | |
toDigitsRev = unfoldr $ \x -> | |
if divMod x 10 == (0, 0) | |
then Nothing | |
else Just $ swap $ divMod x 10 |
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 | |
import Data.Tuple | |
toDigits :: Integer -> [Integer] | |
toDigits = reverse . toDigitsRev | |
toDigitsRev :: Integer -> [Integer] | |
toDigitsRev = unfoldr $ maybeSwap' . splitLastDigit | |
where | |
maybeSwap' = uncurry maybeSwap | |
splitLastDigit = (`divMod` 10) | |
maybeSwap :: Integer -> Integer -> Maybe (Integer, Integer) | |
maybeSwap 0 0 = Nothing | |
maybeSwap x y = Just (y, x) | |
main = do | |
putStrLn $ show $ toDigits 12345 |
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 | |
import Data.Tuple | |
toDigits x = reverse $ unfoldr (\y -> let z = swap (divMod y 10) in if z == (0, 0) then Nothing else Just z) x | |
doubleEveryOther xs = reverse $ map (uncurry (*)) $ zip (reverse xs) (cycle [1, 2]) | |
sumDigits xs = sum $ concatMap (toDigits) xs | |
validate x = (== 0) $ (`mod` 10) $ sumDigits $ doubleEveryOther $ toDigits x | |
main = do | |
putStrLn $ show $ validate 101071 -- True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment