barbara
barbara

Reputation: 3201

Haskell: How to filter a list of list?

Given a list of list:

xss = [[1,2,3],[4,5,6],[7,8]]

I want to filter it by list size then by remainder and then return a list of Int.

Here are my two attempts:

concat [[x | x <- xs, mod x 2 == 0] | xs <- xss, length xs > 2]

filter (\x -> mod x 2 == 0) $ concat $ filter (\x -> length x > 2) xss

Is there more expressive way to do the same but with less code?

Upvotes: 1

Views: 431

Answers (2)

Karl Bielefeldt
Karl Bielefeldt

Reputation: 49008

There's a built-in even function in Haskell, and you can also get help converting to point-free style using Blunt. This gives you:

filter even . concat . filter ((> 2) . length)

Upvotes: 5

chi
chi

Reputation: 116139

A single list comprehension suffices

[x | xs@(_:_:_:_) <- xss, x <- xs, mod x 2 == 0]

The pattern (_:_:_:_) matches all lists having at least three elements.

Upvotes: 3

Related Questions