Search code examples
haskellsyntaxtypesrecord

Haskell record syntax returning a record with specified field value


I am new to Haskell and StackOverflow. I have a 'database' of books. I am trying to return the list of fans of a specified book.

type Title = String
type Author = String
type Year = Int
type Fan = String


data Book = Book { bookTitle :: Title
                 , bookAuthor:: Author
                 , bookYear  :: Year
                 , bookFans  :: [Fan]
                 }
                 deriving (Show)


type Database = [Book]

bookDatabase :: Database 
bookDatabase = [Book "Harry Potter" "JK Rowling" 1997 ["Sarah","Dave"]]

I am not sure how to do this. I have tried using the filter function. I would like the below behavior.

fansOfBook :: Title -> Database -> [Fan]

fansOfBook "Harry Potter"
["Sarah","Dave"] 

Solution

  • What you have to do is a filter operation on your Database:

    filter (\x -> (bookTitle x) == title) db
    

    where db is of type Database and title is of type Title which you are giving as input.

    That will give you a list of all [Book] with that specific title. Now you have to extract out the Fan from it using a map function. But note that this will give you a type of [[Fan]] as you can have multiple entries with the same title. So, you have to apply concat to get them as [Fan]. The function concat will concatenate the list of lists into a singe list.