Avatar of atmantree

atmantree's solution

to ISBN Verifier in the Haskell Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

The ISBN-10 verification process 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:

(x1 * 10 + x2 * 9 + x3 * 8 + x4 * 7 + x5 * 6 + x6 * 5 + x7 * 4 + x8 * 3 + x9 * 2 + x10 * 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:

(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.

Bonus tasks

  • Generate a valid ISBN-13 from the input ISBN-10 (and maybe verify it again with a derived verifier).

  • Generate valid ISBN, maybe even from a given starting ISBN.

Getting Started

For installation and learning resources, refer to the exercism help page.

Running the tests

To run the test suite, execute the following command:

stack test

If you get an error message like this...

No .cabal file found in directory

You are probably running an old stack version and need to upgrade it.

Otherwise, if you get an error message like this...

No compiler found, expected minor version match with...
Try running "stack setup" to install the correct GHC...

Just do as it says and it will download and install the correct compiler version:

stack setup

Running GHCi

If you want to play with your solution in GHCi, just run the command:

stack ghci

Feedback, Issues, Pull Requests

The exercism/haskell repository on GitHub is the home for all of the Haskell exercises.

If you have feedback about an exercise, or want to help implementing a new one, head over there and create an issue. We'll do our best to help you!

Source

Converting a string into a number and some basic processing utilizing a relatable real world example. https://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digit_calculation

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

Tests.hs

{-# LANGUAGE RecordWildCards #-}

import Data.Foldable     (for_)
import Test.Hspec        (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)

import IsbnVerifier (isbn)

main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs

specs :: Spec
specs = describe "isbn" $ for_ cases test
  where

    test Case{..} = it description assertion
      where
        assertion = isbn input `shouldBe` expected

data Case = Case { description :: String
                 , input       :: String
                 , expected    :: Bool
                 }

cases :: [Case]
cases = [ Case { description = "valid isbn number"
               , input       = "3-598-21508-8"
               , expected    = True
               }
        , Case { description = "invalid isbn check digit"
               , input       = "3-598-21508-9"
               , expected    = False
               }
        , Case { description = "valid isbn number with a check digit of 10"
               , input       = "3-598-21507-X"
               , expected    = True
               }
        , Case { description = "check digit is a character other than X"
               , input       = "3-598-21507-A"
               , expected    = False
               }
        , Case { description = "invalid character in isbn"
               , input       = "3-598-P1581-X"
               , expected    = False
               }
        , Case { description = "X is only valid as a check digit"
               , input       = "3-598-2X507-9"
               , expected    = False
               }
        , Case { description = "valid isbn without separating dashes"
               , input       = "3598215088"
               , expected    = True
               }
        , Case { description = "isbn without separating dashes and X as check digit"
               , input       = "359821507"
               , expected    = False
               }
        , Case { description = "too long isbn and no dashes"
               , input       = "3598215078X"
               , expected    = False
               }
        , Case { description = "isbn without check digit"
               , input       = "3-598-21507"
               , expected    = False
               }
        , Case { description = "too long isbn"
               , input       = "3-598-21507-XX"
               , expected    = False
               }
        , Case { description = "check digit of X should not be used for 0"
               , input       = "3-598-21515-X"
               , expected    = False
               }
        , Case { description = "empty isbn"
               , input       = ""
               , expected    = False
               }
        , Case { description = "input is 9 characters"
               , input       = "134456729"
               , expected    = False
               }
        ]
module IsbnVerifier (isbn) where

import Data.List
import Data.Char

removeDash :: [Char] -> [Char]
removeDash = filter ('-' /=)

strToInt :: Char -> Int
strToInt 'X' = 10
strToInt d = digitToInt d

isTenLength :: [Char] -> Bool
isTenLength l = length l == 10

areValidChars :: [Char] -> Bool
areValidChars str = foldl (&&) True (map (\x -> elem x "0123456789") (init str))
                    &&  elem (last str) "0123456789X"

isValid :: [Char] -> Bool
isValid str = isTenLength str_wd && areValidChars str_wd
              where str_wd = removeDash str

isbn :: String -> Bool
isbn code = if isValid code then
                sum (zipWith (*) [10,9..1] numISBN) `mod` 11 == 0 
            else
                False
            where numISBN = [ strToInt x | x <- removeDash code]

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?