1

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
Max
  • 13
  • 3
  • 2
    `xs` is a list, not a function, so the composition `stuff . xs` does not make sense. You can instead use something like `f . g . h $ xs` for `f (g (h xs))`. – chi Mar 07 '22 at 18:04
  • 1
    not strictly a duplicate, but useful reading here: https://stackoverflow.com/questions/940382/what-is-the-difference-between-dot-and-dollar-sign – Robin Zigmond Mar 07 '22 at 18:40
  • 2
    If you can use `concatMap` instead of `map` and `filter`, the Haskell Report tells you how to desugar [list comprehension](https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-420003.11). – chepner Mar 07 '22 at 19:52

1 Answers1

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
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555