Jump to content

ISBN13 check digit: Difference between revisions

no edit summary
No edit summary
Line 166:
978-1788399083: bad
</pre>
=={{header|Haskell}}==
Uses Data.List.Split library: https://hackage.haskell.org/package/split-0.2.3.4/docs/Data-List-Split.html
<lang haskell>
import Data.List.Split (chunksOf)
import Data.Char (isDigit, digitToInt)
import Control.Monad (forM_)
import Text.Printf (printf)
 
testISBNs :: [String]
testISBNs =
[ "978-1734314502" -- good
, "978-1734314509" -- bad
, "978-1788399081" -- good
, "978-1788399083" -- bad
]
 
validIsbn13 :: String -> Bool
validIsbn13 isbn
| length (digits isbn) /= 13 = False
| otherwise = calc isbn `rem` 10 == 0
where digits = map digitToInt . filter isDigit
calc = foldl (\a b -> if length b == 2
then head b + (head $ reverse b) * 3 + a
else head b + a) 0 . chunksOf 2 . digits
 
main :: IO ()
main = forM_ testISBNs (\isbn -> printf "%s: Valid: %s\n" isbn (show $ validIsbn13 isbn))
</lang>
{{out}}
<pre>
978-1734314502: Valid: True
978-1734314509: Valid: False
978-1788399081: Valid: True
978-1788399083: Valid: False
</pre>
=={{header|Julia}}==
<lang julia>function isbncheck(str)
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.