Haskell: searching though fst in a tuple and displaying the snd -


i have database of films so:

testdatabase = [("blade runner", "ridley scott", 1982, [("amy",6), ("bill",9), ("ian",7), ("kevin",9), ("emma",4), ("sam",5), ("megan",4)]), ("the fly", "david cronenberg", 1986, [("megan",4), ("fred",7), ("chris",5), ("ian",0), ("amy",5)])] 

it contains 2 films in format: 'title', 'director', 'year', 'user rating'

type userrating = [(string, int)] 

i have function called 'displayallfilms' display each film in formatted string. , function 'hasuserrated' returns bool if user has rated:

hasuserrated :: string -> film -> bool hasuserrated user (_, _, _, userrating)         | elem user (map fst (userrating)) = true         | otherwise                        = false 

if do: displayallfilms $ filter (hasuserrated "amy") database return films amy has rated (blade runner & fly)

i need display rating when finds amy's tuple.

to tackle have function called whatuserrated:

    whatuserrated ::  string -> film -> [int]     whatuserrated user (_, _, _, userrating)          | elem user (map fst (userrating)) = map snd userrating 

my question:

i need change above function return 1 int, int of 'snd' in tuple element 'user' (amy) found. i.e need to:

whatuserrated "amy" (i need result of filter second parameter)

the below function can see in context:

userratedfilms :: string -> database -> string userratedfilms user database = displayallfilms $ map (whatuserrated "amy") $ filter (hasuserrated "amy") testdatabase 

so far, above return ratings in films amy has rated,

however, want ratings. hope have explained enough, english not excellent.

thank you,

mike.

the function you're looking called lookup. has type

lookup :: eq => -> [(a, b)] -> maybe b 

basically, takes association list , returns first result given key matches first element in 1 of tuples. if no such tuple found, returns nothing. example usage be

> lookup 3 [(1, "one"), (2, "two"), (3, "three")] "three" > lookup 4 [(1, "one"), (2, "two"), (3, "three")] nothing 

one of handy things maybe data type can use filter data. if operation returns nothing, discard it, otherwise use value. example, write functions as

whatuserrated :: string -> film -> maybe int whatuserrated = user (_, _, _, userrating) = lookup user userrating  hasuserrated :: string -> film -> bool hasuserrated user film = isjust $ whatuserrated user film 

just make sure import data.maybe.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -