Hi, I am trying to do some exercies in my Haskell book. I couldn't get my program to work correctly. type Database2 = [ (Person,[ Book ]) ] exampleBase2 :: Database2 exampleBase2 = [ ("Alice", [ "Tintin", "Astrix" ] ), ("Anna", [ "Little Woman" ] ), ("Rory", [ "Tintin" ] ) ] books2 :: Database2 -> Person -> [Book] books2 db person = head [ snd tuple | tuple <- db, fst tuple == person ] borrowers2 :: Database2 -> Book -> [Person] borrowers2 db book = [ person | (person, books) <- db, book <- books ] borrowers2 function should return the names of people that borrowed the "book". However my implementation lists all the people. Book, and Person are of type String. Also could you comment on the quality of the implementation of "books2" function, which is supposed to return the name of the books that a person borrowed (It is working correctly). Thanks
Cagdas Ozgenc wrote:
books2 :: Database2 -> Person -> [Book]
books2 db person = head [ snd tuple | tuple <- db, fst tuple == person ]
borrowers2 :: Database2 -> Book -> [Person] borrowers2 db book = [ person | (person, books) <- db, book <- books ]
You can't pattern match against a variable (like equal x x = True). But that is what you seem to be doing in book <- books. However, Haskell doesn't give you an error in this case (as it would with my equal example) because the book in book <- books is considered a new veriable that is hiding the other book variable. What you wrote is the same as
borrowers2 db book = [ person | (person, books) <- db, x <- books ]
where x <- books has no meaning (except maybe the person should have at least one book). Try this instead:
borrowers2 db book = [ person | (person, books) <- db, elem book books]
As for books2, use (person, books) <- db instead of tuple. Looks better than fst and snd in my opinion. Tom
participants (2)
-
Cagdas Ozgenc -
Tom Schrijvers