Skip to content

Instantly share code, notes, and snippets.

@gnusosa
Created December 16, 2014 23:51
Show Gist options
  • Select an option

  • Save gnusosa/8694634d9adeb8f0bf5d to your computer and use it in GitHub Desktop.

Select an option

Save gnusosa/8694634d9adeb8f0bf5d to your computer and use it in GitHub Desktop.
import Data.Digits
import Data.Maybe
data Isbn = Isbn { isbn10 :: Maybe Isbn10
, isbn13 :: Maybe Isbn13 }
deriving (Eq, Show)
data Isbn10 = Isbn10 Int deriving (Eq, Show)
data Isbn13 = Isbn13 Int deriving (Eq, Show)
mkValidIsbn10 :: Int -> Maybe Isbn10
mkValidIsbn10 n
| d == 10 = Just $ Isbn10 n
| otherwise = Nothing
where d = length $ digits 10 n
mkValidIsbn13 :: Int -> Maybe Isbn13
mkValidIsbn13 n
| d == 13 = Just $ Isbn13 n
| otherwise = Nothing
where d = length $ digits 10 n
getIsbn10 :: Maybe Isbn10 -> Int
getIsbn10 (Just (Isbn10 a)) = a
getIsbn13 :: Maybe Isbn13 -> Int
getIsbn13 (Just (Isbn13 a)) = a
notValidIntError :: Int -> String
notValidIntError n = "Cant create a valid ISBN from " ++ show n
mkValidIsbn :: Int -> Isbn
mkValidIsbn n | isbn10 a == Nothing && isbn13 a == Nothing = error $ notValidIntError n
| otherwise = a
where a = Isbn (mkValidIsbn10 n) (mkValidIsbn13 n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment