j :: (Ord a) => [(a,a)] -> a -> [a] j xs x = [ v | (u,v) <- xs, u == x]
This code displays a list of the second elements of every tuple in xs based on the first element of the tuple (x).
For my assignment, I should define this in terms of higher order functions map and/or filter.
I came up with
j xs x = map snd . filter (\(a,_) -> a == x). xs
But I get errors regarding the type signature.
Can you help me modify this into the type signature mentioned above and any other changes? Thank you
CodePudding user response:
You can solve this by using parthesis and remove the last dot (.
) before the xs
:
j :: Eq a => [(a, b)] -> a -> [b]
j xs x = (map snd . filter ((a,_) -> a == x)) xs
here we thus construct a function between the parenthesis, and we use xs
as argument. If you use f . x
, then because of (.) :: (b -> c) -> (a -> b) -> a -> c
, it expects x
to be a function and it constructs a new function, but in your case xs
is an argument, not another function to a use in the "chain".
The (a, _) -> a == x
, can be replaced by (x ==) . fst
:
j :: Eq a => [(a, b)] -> a -> [b]
j xs x = (map snd . filter ((x ==) . fst)) xs