4 ms·
Being pedantic: This isn't true in Haskell, because list comprehensions can use pattern matching, while map+filter can't. heads :: [[a]] -> [a] heads xs =
by ogogmad 4y ago
Being pedantic: This isn't true in Haskell, because list comprehensions can use pattern matching, while map+filter can't.
heads :: [[a]] -> [a]
heads xs = [y | (y:ys) <- xs]
-- heads [[1],[],[2,3]] == [1,2]
Doing the above using maps and filters looks very different:
heads' = map head . filter (not . null)
Python doesn't really support Haskell-like pattern matching, so the above doesn't apply.
- pdonis 4y ago> Python doesn't really support Haskell-like pattern matching It does as of 3.10: https://peps.python.org/pep-0622/ https://peps.python.org/pep-0622/ Not as sophisticated as what Haskell can do, I'm sure, but I think it's a good addition to Python.
- _v7gu 4y agoThe thing you're looking for is easily found with a Hoogle search for type (a -> Maybe b) -> [a] -> [b] Which yields mapMaybe: https://hackage.haskell.org/package/base-4.17.0.0/docs/Data-Maybe.html#v:mapMaybe https://hackage.haskell.org/package/base-4.17.0.0/docs/Data-.... so you end up with heads = mapMaybe safeHead
- ogogmad 4y agoThat doesn't look like a direct substitute that covers every case.