'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


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Willem Van Onsem