Skip to content

Commit

Permalink
Add isbn-verifier exercise (#251)
Browse files Browse the repository at this point in the history
  • Loading branch information
keiravillekode authored Dec 23, 2023
1 parent 0122858 commit 23cfd80
Show file tree
Hide file tree
Showing 8 changed files with 383 additions and 0 deletions.
9 changes: 9 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,15 @@
"math"
]
},
{
"slug": "isbn-verifier",
"name": "Isbn Verifier",
"uuid": "38a13f45-9e80-4322-b896-d2cf06add3f9",
"practices": [],
"prerequisites": [],
"difficulty": 3,
"topics": []
},
{
"slug": "matching-brackets",
"name": "Matching Brackets",
Expand Down
42 changes: 42 additions & 0 deletions exercises/practice/isbn-verifier/.docs/instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Instructions

The [ISBN-10 verification process][isbn-verification] is used to validate book identification numbers.
These normally contain dashes and look like: `3-598-21508-8`

## ISBN

The ISBN-10 format is 9 digits (0 to 9) plus one check character (either a digit or an X only).
In the case the check character is an X, this represents the value '10'.
These may be communicated with or without hyphens, and can be checked for their validity by the following formula:

```text
(d₁ * 10 + d₂ * 9 + d₃ * 8 + d₄ * 7 + d₅ * 6 + d₆ * 5 + d₇ * 4 + d₈ * 3 + d₉ * 2 + d₁₀ * 1) mod 11 == 0
```

If the result is 0, then it is a valid ISBN-10, otherwise it is invalid.

## Example

Let's take the ISBN-10 `3-598-21508-8`.
We plug it in to the formula, and get:

```text
(3 * 10 + 5 * 9 + 9 * 8 + 8 * 7 + 2 * 6 + 1 * 5 + 5 * 4 + 0 * 3 + 8 * 2 + 8 * 1) mod 11 == 0
```

Since the result is 0, this proves that our ISBN is valid.

## Task

Given a string the program should check if the provided string is a valid ISBN-10.
Putting this into place requires some thinking about preprocessing/parsing of the string prior to calculating the check digit for the ISBN.

The program should be able to verify ISBN-10 both with and without separating dashes.

## Caveats

Converting from strings to numbers can be tricky in certain languages.
Now, it's even trickier since the check digit of an ISBN-10 may be 'X' (representing '10').
For instance `3-598-21507-X` is a valid ISBN-10.

[isbn-verification]: https://en.wikipedia.org/wiki/International_Standard_Book_Number
19 changes: 19 additions & 0 deletions exercises/practice/isbn-verifier/.meta/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"authors": [
"keiravillekode"
],
"files": {
"solution": [
"isbn-verifier.sml"
],
"test": [
"test.sml"
],
"example": [
".meta/example.sml"
]
},
"blurb": "Check if a given string is a valid ISBN-10 number.",
"source": "Converting a string into a number and some basic processing utilizing a relatable real world example.",
"source_url": "https://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digit_calculation"
}
15 changes: 15 additions & 0 deletions exercises/practice/isbn-verifier/.meta/example.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
val isValid: string -> bool =
let
fun digitValue (c: char): int =
Char.ord c - Char.ord #"0"
val excludeHyphens: char list -> char list =
List.filter (fn c => c <> #"-")
fun recurse (weight: int) (total: int) (l: char list): bool =
case (weight, l) of
(0, nil) => total mod 11 = 0
| (_, nil) => false
| (1, #"X" :: nil) => total mod 11 = 1
| (_, c :: rest) => Char.isDigit c andalso recurse (weight - 1) (total + weight * (digitValue c)) rest
in
recurse 10 0 o excludeHyphens o String.explode
end
67 changes: 67 additions & 0 deletions exercises/practice/isbn-verifier/.meta/tests.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# This is an auto-generated file.
#
# Regenerating this file via `configlet sync` will:
# - Recreate every `description` key/value pair
# - Recreate every `reimplements` key/value pair, where they exist in problem-specifications
# - Remove any `include = true` key/value pair (an omitted `include` key implies inclusion)
# - Preserve any other key/value pair
#
# As user-added comments (using the # character) will be removed when this file
# is regenerated, comments can be added via a `comment` key.

[0caa3eac-d2e3-4c29-8df8-b188bc8c9292]
description = "valid isbn"

[19f76b53-7c24-45f8-87b8-4604d0ccd248]
description = "invalid isbn check digit"

[4164bfee-fb0a-4a1c-9f70-64c6a1903dcd]
description = "valid isbn with a check digit of 10"

[3ed50db1-8982-4423-a993-93174a20825c]
description = "check digit is a character other than X"

[9416f4a5-fe01-4b61-a07b-eb75892ef562]
description = "invalid check digit in isbn is not treated as zero"

[c19ba0c4-014f-4dc3-a63f-ff9aefc9b5ec]
description = "invalid character in isbn is not treated as zero"

[28025280-2c39-4092-9719-f3234b89c627]
description = "X is only valid as a check digit"

[f6294e61-7e79-46b3-977b-f48789a4945b]
description = "valid isbn without separating dashes"

[185ab99b-3a1b-45f3-aeec-b80d80b07f0b]
description = "isbn without separating dashes and X as check digit"

[7725a837-ec8e-4528-a92a-d981dd8cf3e2]
description = "isbn without check digit and dashes"

[47e4dfba-9c20-46ed-9958-4d3190630bdf]
description = "too long isbn and no dashes"

[737f4e91-cbba-4175-95bf-ae630b41fb60]
description = "too short isbn"

[5458a128-a9b6-4ff8-8afb-674e74567cef]
description = "isbn without check digit"

[70b6ad83-d0a2-4ca7-a4d5-a9ab731800f7]
description = "check digit of X should not be used for 0"

[94610459-55ab-4c35-9b93-ff6ea1a8e562]
description = "empty isbn"

[7bff28d4-d770-48cc-80d6-b20b3a0fb46c]
description = "input is 9 characters"

[ed6e8d1b-382c-4081-8326-8b772c581fec]
description = "invalid characters are not ignored after checking length"

[daad3e58-ce00-4395-8a8e-e3eded1cdc86]
description = "invalid characters are not ignored before checking length"

[fb5e48d8-7c03-4bfb-a088-b101df16fdc3]
description = "input is too long but contains a valid isbn"
2 changes: 2 additions & 0 deletions exercises/practice/isbn-verifier/isbn-verifier.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
fun isValid (isbn: string): bool =
raise Fail "'isValid' is not implemented"
69 changes: 69 additions & 0 deletions exercises/practice/isbn-verifier/test.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
(* version 1.0.0 *)

use "testlib.sml";
use "isbn-verifier.sml";

infixr |>
fun x |> f = f x

val testsuite =
describe "isbn-verifier" [
test "valid isbn"
(fn _ => isValid "3-598-21508-8" |> Expect.truthy),

test "invalid isbn check digit"
(fn _ => isValid "3-598-21508-9" |> Expect.falsy),

test "valid isbn with a check digit of 10"
(fn _ => isValid "3-598-21507-X" |> Expect.truthy),

test "check digit is a character other than X"
(fn _ => isValid "3-598-21507-A" |> Expect.falsy),

test "invalid check digit in isbn is not treated as zero"
(fn _ => isValid "4-598-21507-B" |> Expect.falsy),

test "invalid character in isbn is not treated as zero"
(fn _ => isValid "3-598-P1581-X" |> Expect.falsy),

test "X is only valid as a check digit"
(fn _ => isValid "3-598-2X507-9" |> Expect.falsy),

test "valid isbn without separating dashes"
(fn _ => isValid "3598215088" |> Expect.truthy),

test "isbn without separating dashes and X as check digit"
(fn _ => isValid "359821507X" |> Expect.truthy),

test "isbn without check digit and dashes"
(fn _ => isValid "359821507" |> Expect.falsy),

test "too long isbn and no dashes"
(fn _ => isValid "3598215078X" |> Expect.falsy),

test "too short isbn"
(fn _ => isValid "00" |> Expect.falsy),

test "isbn without check digit"
(fn _ => isValid "3-598-21507" |> Expect.falsy),

test "check digit of X should not be used for 0"
(fn _ => isValid "3-598-21515-X" |> Expect.falsy),

test "empty isbn"
(fn _ => isValid "" |> Expect.falsy),

test "input is 9 characters"
(fn _ => isValid "134456729" |> Expect.falsy),

test "invalid characters are not ignored after checking length"
(fn _ => isValid "3132P34035" |> Expect.falsy),

test "invalid characters are not ignored before checking length"
(fn _ => isValid "3598P215088" |> Expect.falsy),

test "input is too long but contains a valid isbn"
(fn _ => isValid "98245726788" |> Expect.falsy)
]

val _ = Test.run testsuite
160 changes: 160 additions & 0 deletions exercises/practice/isbn-verifier/testlib.sml
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
structure Expect =
struct
datatype expectation = Pass | Fail of string * string

local
fun failEq b a =
Fail ("Expected: " ^ b, "Got: " ^ a)

fun failExn b a =
Fail ("Expected: " ^ b, "Raised: " ^ a)

fun exnName (e: exn): string = General.exnName e
in
fun truthy a =
if a
then Pass
else failEq "true" "false"

fun falsy a =
if a
then failEq "false" "true"
else Pass

fun equalTo b a =
if a = b
then Pass
else failEq (PolyML.makestring b) (PolyML.makestring a)

fun nearTo delta b a =
if Real.abs (a - b) <= delta * Real.abs a orelse
Real.abs (a - b) <= delta * Real.abs b
then Pass
else failEq (Real.toString b ^ " +/- " ^ Real.toString delta) (Real.toString a)

fun anyError f =
(
f ();
failExn "an exception" "Nothing"
) handle _ => Pass

fun error e f =
(
f ();
failExn (exnName e) "Nothing"
) handle e' => if exnMessage e' = exnMessage e
then Pass
else failExn (exnMessage e) (exnMessage e')
end
end

structure TermColor =
struct
datatype color = Red | Green | Yellow | Normal

fun f Red = "\027[31m"
| f Green = "\027[32m"
| f Yellow = "\027[33m"
| f Normal = "\027[0m"

fun colorize color s = (f color) ^ s ^ (f Normal)

val redit = colorize Red

val greenit = colorize Green

val yellowit = colorize Yellow
end

structure Test =
struct
datatype testnode = TestGroup of string * testnode list
| Test of string * (unit -> Expect.expectation)

local
datatype evaluation = Success of string
| Failure of string * string * string
| Error of string * string

fun indent n s = (implode (List.tabulate (n, fn _ => #" "))) ^ s

fun fmt indentlvl ev =
let
val check = TermColor.greenit "\226\156\148 " (**)
val cross = TermColor.redit "\226\156\150 " (**)
val indentlvl = indentlvl * 2
in
case ev of
Success descr => indent indentlvl (check ^ descr)
| Failure (descr, exp, got) =>
String.concatWith "\n" [indent indentlvl (cross ^ descr),
indent (indentlvl + 2) exp,
indent (indentlvl + 2) got]
| Error (descr, reason) =>
String.concatWith "\n" [indent indentlvl (cross ^ descr),
indent (indentlvl + 2) (TermColor.redit reason)]
end

fun eval (TestGroup _) = raise Fail "Only a 'Test' can be evaluated"
| eval (Test (descr, thunk)) =
(
case thunk () of
Expect.Pass => ((1, 0, 0), Success descr)
| Expect.Fail (s, s') => ((0, 1, 0), Failure (descr, s, s'))
)
handle e => ((0, 0, 1), Error (descr, "Unexpected error: " ^ exnMessage e))

fun flatten depth testnode =
let
fun sum (x, y, z) (a, b, c) = (x + a, y + b, z + c)

fun aux (t, (counter, acc)) =
let
val (counter', texts) = flatten (depth + 1) t
in
(sum counter' counter, texts :: acc)
end
in
case testnode of
TestGroup (descr, ts) =>
let
val (counter, texts) = foldr aux ((0, 0, 0), []) ts
in
(counter, (indent (depth * 2) descr) :: List.concat texts)
end
| Test _ =>
let
val (counter, evaluation) = eval testnode
in
(counter, [fmt depth evaluation])
end
end

fun println s = print (s ^ "\n")
in
fun run suite =
let
val ((succeeded, failed, errored), texts) = flatten 0 suite

val summary = String.concatWith ", " [
TermColor.greenit ((Int.toString succeeded) ^ " passed"),
TermColor.redit ((Int.toString failed) ^ " failed"),
TermColor.redit ((Int.toString errored) ^ " errored"),
(Int.toString (succeeded + failed + errored)) ^ " total"
]

val status = if failed = 0 andalso errored = 0
then OS.Process.success
else OS.Process.failure

in
List.app println texts;
println "";
println ("Tests: " ^ summary);
OS.Process.exit status
end
end
end

fun describe description tests = Test.TestGroup (description, tests)
fun test description thunk = Test.Test (description, thunk)

0 comments on commit 23cfd80

Please sign in to comment.