Skip to content

Instantly share code, notes, and snippets.

@Rembane
Created June 26, 2014 23:13
Show Gist options
  • Save Rembane/d4304c938f0751768888 to your computer and use it in GitHub Desktop.
Save Rembane/d4304c938f0751768888 to your computer and use it in GitHub Desktop.
Just fooling around with personnummer-validation.
import Data.Char
import Data.List
type Personnummer = [Int]
mod10 x = mod x 10
cleanAndConvert :: String -> Maybe Personnummer
cleanAndConvert cs = return $ map digitToInt $ filter isDigit cs
validateLength :: Personnummer -> Maybe Personnummer
validateLength xs | (length xs) `elem` [10, 12] = find (\x -> (length x) == 10) $ tails xs
| otherwise = Nothing
validateLuhn :: Personnummer -> Maybe Personnummer
validateLuhn xs | last xs == result = return xs
| otherwise = Nothing
where
xs' = take 9 xs
result = mod10 $ 10 - (mod10 $ sum $ map (uncurry (+)) $ zipWith (\a b -> divMod (a*b) 10) (cycle [2,1]) xs')
validate :: String -> Maybe Personnummer
validate s = (cleanAndConvert s) >>= validateLength >>= validateLuhn
main = do
putStrLn "Vänligen ange ett personnummer: "
s <- getLine
case validate s of
Just _ -> putStrLn "Grattis, ditt personnummer validerar!"
Nothing -> putStrLn "Tyvärr validerar inte ditt personnummer. Försök igen!"
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment