List of Tuples as a function Parameter in Haskell -
List of Tuples as a function Parameter in Haskell -
how define function parameter list of tuples? illustration of input
[("hey", false), ("you", true)]
my function takes list of tuples as: [(string, bool)] here looks like:
afunc :: [(string, bool)] -> bool afunc ???? =
so fill in ???? able access tuple? help great. thanks.
edit:
afunc :: [(string, bool)] -> bool afunc atuple = mapm_ lookup atuple?
so how access tuple in function? doesn't work.
it looks you're trying implement own version of lookup
. can write 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 these versions unsafe - is, they'll fail ugly , uninformative error if list doesn't contain item:
ghci> lookup' "foo" [("bar",true)] *** exception: prelude.head: empty list
you can solve issue writing 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 improve approach homecoming maybe bool
instead:
lookupmaybe :: string -> [(string,bool)] -> maybe bool lookupmaybe k lkp = case [v | (k',v) <- lkp, k'==k] of (v:_) -> v [] -> nil
the library version takes approach, , has more generic signature:
lookup :: (eq a) => -> [(a,b)] -> maybe b
you can read implementation here.
list function haskell parameters tuples
Comments
Post a Comment