Created
May 22, 2015 07:23
-
-
Save ThomasLocke/bc39dea5300f220c91be to your computer and use it in GitHub Desktop.
Playing around with Haskell type/data and a couple of simple functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | |
-- 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