ISBN13 check digit: Difference between revisions

m
(Add Refal)
 
(5 intermediate revisions by 3 users not shown)
Line 1,970:
=={{header|langur}}==
In this example, we map to multiple functions (actually 1 no-op).
<syntaxhighlight lang="langur">val .isbn13checkdigit = ffn(var .s) {
.s = replace(.s, RE/[\- ]/)
.s -> re/^[0-9]{13}$/ and
fold(ffn{+}, map [_, ffn{x *3}], s2n .s) div 10
}
 
val .tests = h{
"978-0596528126": true,
"978-0596528120": false,
"978-1788399081": true,
"978-1788399083": false,
}
 
for .key of .tests {
val .pass = .isbn13checkdigit(.key)
write .key, ": ", if(.pass: "good"; "bad")
writeln if(.pass == .tests[.key]: ""; " (ISBN-13 CHECK DIGIT TEST FAILED)")
}</syntaxhighlight>
 
In this example, we set a for loop value as it progresses.
<syntaxhighlight lang="langur">val .isbn13checkdigit = f(var .s) {
.s = replace(.s, RE/[\- ]/)
var .alt = true
.s -> re/^[0-9]{13}$/ and
for[=0] .d in s2n(.s) { _for += if(not= .alt: .d x 3; .d) } div 10
}
 
val .tests = h{
"978-0596528126": true,
"978-0596528120": false,
Line 2,114 ⟶ 2,093:
978-1788399081 good
978-1788399083 bad</pre>
 
=={{header|Miranda}}==
<syntaxhighlight lang="smlmiranda">localmain :: [sys_message]
main = [Stdout (lay (map test tests))]
 
test :: [char]->[char]
test isbn = isbn ++ ": good", if isbn13 isbn
= isbn ++ ": bad", otherwise
 
tests :: [[char]]
tests = ["978-0596528126",
"978-0596528120": false,
"978-1788399081": true,
"978-1788399083": false,]
 
isbn13 :: [char]->bool
isbn13 str = False, if #isbn ~= 13 \/ ~and (map digit isbn)
= check mod 10 = 0, otherwise
where isbn = filter (~= '-') str
digits = map (numval.(:[])) isbn
check = sum (zipwith (*) digits (concat (repeat [1,3])))
 
uncurry :: (*->**->***)->(*,**)->***
uncurry f (a,b) = f a b
 
zipwith :: (*->**->***)->[*]->[**]->[***]
zipwith f a b = map (uncurry f) (zip2 a b)</syntaxhighlight>
{{out}}
"<pre>978-0596528126": true,good
978-0596528120: bad
978-1788399081: good
978-1788399083: bad</pre>
 
=={{header|Modula-2}}==
Line 3,019 ⟶ 3,030:
 
=={{header|Standard ML}}==
===Easy to read version===
<syntaxhighlight lang="sml">local
<syntaxhighlight lang="sml">(* these type decorations are optional, you could just as well put:
fun isValidISBN s =
*)
fun isValidISBN (s : string) : bool =
let
val digits = List.filter Char.isDigit (explode s)
val nums = map (fn x => ord x - ord #"0") digits
val len = length nums
fun sumISBN [] = raise Domain
| sumISBN [x] = x
| sumISBN (x1::x2::xs) = x1 + 3*x2 + sumISBN xs
in
len = 13 andalso sumISBN nums mod 10 = 0
end
 
val test = ["978-1734314502", "978-1734314509",
"978-1788399081", "978-1788399083"]
 
fun printTest (s : string) : unit =
(print s; print (if isValidISBN s then ": good\n" else ": bad\n"))
 
fun main () = app printTest test</syntaxhighlight>
 
===Original version===
}</syntaxhighlight lang="sml">let
fun check (c, p as (m, n)) =
if Char.isDigit c then
885

edits