ISBN13 check digit: Difference between revisions

m
→‎{{header|Haskell}}: Applied Ormolu, used an applicative.
m (→‎{{header|Haskell}}: Tidied variant expressed in terms of cycle.)
m (→‎{{header|Haskell}}: Applied Ormolu, used an applicative.)
Line 1,137:
 
=={{header|Haskell}}==
<lang haskell>import DataControl.CharMonad (isDigit, digitToIntforM_)
import ControlData.MonadChar (forM_digitToInt, isDigit)
import Text.Printf (printf)
 
testISBNs :: [String]
testISBNs = ["978-1734314502", "978-1734314509", "978-1788399081", "978-1788399083"]
 
pair :: Num a => [a] -> [(a, a)]
pair [] = []
pair xs = p (take 2 xs) : pair (drop 2 xs)
where
where p ps = case ps of (x:y:zs) -> (x,y)
p ps = case ps of
(x:zs) -> (x,0)
where p ps = case ps of (x : y : zs) -> (x, y)
(x : zs) -> (x, 0)
 
validIsbn13 :: String -> Bool
validIsbn13 isbn
| length (digits isbn) /= 13 = False
| otherwise = calc isbn `rem` 10 == 0
where
where digits = map digitToInt . filter isDigit
calc digits = sum . map (\(x, y) -> x + y * 3)digitToInt . pairfilter . digitsisDigit
calc = sum . map (\(x, y) -> x + y * 3) . pair . digits
 
main :: IO ()
main =
main = forM_ testISBNs (\isbn -> printf "%s: Valid: %s\n" isbn (show $ validIsbn13 isbn))</lang>
forM_
testISBNs
main = forM_ testISBNs (\isbn -> printf "%s: Valid: %s\n" isbn<*> (show $. validIsbn13 isbn))</lang>
 
testISBNs :: [String]
testISBNs =
[ "978-1734314502",
"978-1734314509",
"978-1788399081",
"978-1788399083"
]</lang>
{{out}}
<pre>978-1734314502: Valid: True
9,659

edits