haskell - How to search for matching items in a list? -
i'm doing exercise practice exam tomorrow. text tells me implement database library, define item
s can books or magazines. each book save name + author. each magazine
save name:
data item = book string string | magazine string deriving(show) data requisition = req string item type database = [requisition] exdb :: database exdb = [req "john" (book "pf" "hs"),req "jay"(book "apple" "steve jobs"),req "francis"(magazine "forbes")] books :: database -> string -> [item] books db name = {-- what's next?-}
now, need create function named books :: database -> string -> [item]
, searches name on database , gives me books person requested.
how do this?
this straightforward using filter
function:
filter :: (a -> bool) -> [a] -> [a]
it takes condition apply each element of list, returns list of elements meet condition. in case, want books have been requested given person. can break down 2 problems:
- find requests given person
- find books in
requisition
list
to solve first, say
requestsfromperson :: database -> string -> database requestsfromperson db name = filter matchesname db matchesname (req name' item) = name == name'
the second step can done filter
, i'm going let fill in implementation
onlybooks :: database -> database onlybooks db = filter ??? db
then can combine these two:
books db name = onlybooks (requestsfromperson db name)
so have fill in ???
onlybooks
, should work! hint: pattern matching friend.
Comments
Post a Comment