Skip to content

Instantly share code, notes, and snippets.

@ThomasLocke
Created May 22, 2015 07:23
Show Gist options
  • Save ThomasLocke/bc39dea5300f220c91be to your computer and use it in GitHub Desktop.
Save ThomasLocke/bc39dea5300f220c91be to your computer and use it in GitHub Desktop.
Playing around with Haskell type/data and a couple of simple functions
--
-- Lets pretty print a Book!
--
-- A couple of type synonyms for readability.
type Title = String
type Authors = [String]
-- Our Book data type.
-- A book consists of an isbn number, a title and a list of authors.
data Book = Book {isbn :: Int,
title :: Title,
authors :: Authors}
deriving (Show)
-- A convenience method for empty String.
emptyString = ""
-- This is our book.
myBook = Book 42 "Secrets of The Universe" ["Author no. 1", "Authour no. 2"]
-- Constructs a string of authors from the Authors list.
-- Delimiter is a /
getAuthorsString :: String -> Authors -> String
getAuthorsString x xs = if length x == 0 && length xs == 0
then emptyString
else if length x == 0 && length xs == 1
then head xs
else if length x == 0 && length xs > 1
then getAuthorsString (x ++ head xs) (tail xs)
else if length x > 0 && length xs == 1
then x ++ " / " ++ head xs
else if length x > 0 && length xs > 1
then getAuthorsString (x ++ " / " ++ head xs) (tail xs)
else x
-- Take a Book and return it as a prettyfied String representation.
prettyPrint :: Book -> String
prettyPrint b = "The book " ++
title b ++
" (isbn " ++
show (isbn b) ++
") is written by " ++
getAuthorsString (emptyString) (authors b)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment