0
votes

How do define a function with a parameter that is a list of tuples? So an example of the input would be

[("hey", False), ("you", True)]

My function takes the list of tuples as: [(String, Bool)] So here is what it looks like:

aFunc :: [(String, Bool)] -> Bool
aFunc ???? = 

So what do I fill in for the ???? to be able to access my tuple? Any help would be great. Thanks.

Edit:

aFunc :: [(String, Bool)] -> Bool
aFunc aTuple = mapM_ lookup aTuple?

So how do I access my tuple in a function? That doesn't work.

1
The question is too vague. What function are you trying to implement?Benesh
I'm just trying to understand how I can access my tuple. So normally I would do something like; aFunc :: String -> Bool -> Bool aFunc stringInput aBool = case aBool of... I'm asking what I would place in the ???? instead of stringInput or aBool for accessing an item in the tuple list.pmac89
There's nothing special about a list of tuples - you'll have to treat the argument as a list, whose items are, well, tuples :) I'd need some more info for a more specific answer.Benesh
Are you trying to implement a function which takes a string (i.e. "Hey") and return a matching boolean value from the list?Benesh

1 Answers

4
votes

It looks like you're trying to implement your own version of lookup. You can write a simple version using list comprehension:

lookup' :: String -> [(String,Bool)] -> Bool
lookup' k lkp = head $ [v | (k',v) <- lkp, k'==k]

Or using filter:

lookup'' :: String -> [(String,Bool)] -> Bool
lookup'' k lkp = snd $ head $ filter ((==k) . fst) lkp

Notice that these versions are unsafe - that is, they'll fail with an ugly and uninformative error if the list doesn't contain your item:

ghci> lookup' "foo" [("bar",True)]
*** Exception: Prelude.head: empty list

You can solve this issue by writing your own custom error message:

lookupErr :: String -> [(String,Bool)] -> Bool
lookupErr k lkp = case [v | (k',v) <- lkp, k'==k] of
                     (v:_) -> v
                     [] -> error "Key not found!"

A better approach is to return a Maybe Bool instead:

lookupMaybe :: String -> [(String,Bool)] -> Maybe Bool
lookupMaybe k lkp = case [v | (k',v) <- lkp, k'==k] of
                     (v:_) -> Just v
                     [] -> Nothing

The library version takes this approach, and has a more generic signature:

lookup :: (Eq a) => a -> [(a,b)] -> Maybe b

You can read its implementation here.