Reputation: 117
I have created a type in Haskell but I have no idea on how to get one of the fields of my created type. How should I go about? Should I make a function Book -> String
or something like that?
import Data.List
import System.IO
type Book = (Int, String, String, String, String, String, String)
bookNew :: Int -> String -> String-> String -> String -> String -> String -> Book
bookNew isbn title author genre date publisher summary =
(isbn,title,author,genre,date,publisher,summary):: Book
main = do
let book = bookNew 1 "title" "author" "genre" "date" "publisher" "summary"
--Access title of "book" somehow
return book
Upvotes: 3
Views: 4463
Reputation: 6463
If you want to use a type synonym, then you have to manually create functions to retrieve every "field" of your Book
type:
getTitle :: Book -> String
getTitle (_, title, _, _, _, _, _) = title
I would recommend you to create your own data type using record syntax to get such functions for free.
Additionally, when creating such complex type synonyms, you can create other synonyms that represent the individual parts of your main synonym to make clear what the Book
represents.
type Isbn = Int
type Title = String
type Author = String
type Genre = String
type Date = String
type Publisher = String
type Summary = String
type Book = (Isbn, Title, Author, Genre, Date, Publisher, Summary)
Then getTitle
can have the type Book -> Title
Upvotes: 6
Reputation: 10041
I would suggest using records when creating such a large type. Something along the lines of
data Book = Book { pages :: Int
, author :: String
, title :: String
}
at which point, if you ever wanted the author of a book, it is as simple as
main = do
let book = Book 20 "me" "my book"
putStrLn (author book)
which would print the author of your book.
Records essentially create functions that pull out only a single piece of data from your type.
Upvotes: 13