Max
Max

Reputation: 13

Rewrite using higher order functions

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

Upvotes: 1

Views: 123

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476813

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

Upvotes: 1

Related Questions