Home > Enterprise >  Haskell - List comprehension, create/extend tuple list
Haskell - List comprehension, create/extend tuple list

Time:10-18

I'm trying to make compact update rules for a list of tuples.

This is an example of an update rule:

rule1: [(a,b) | (a,b) <- zip [1..3] [2..4]]
λ:[(1,2),(2,3),(3,4)]

What I want:

rule2: [(a,b) (b,a) | (a,b) <- zip [1..3] [2..4]]
λ(expected):[(1,2),(2,1),(2,3),(3,2),(3,4),(4,3)]

Is something like this possible in Haskell's list comprehension?


A possible solution that works, but I find it a bit ugly is:

concat [[(a,b),(b,a)] | (a,b) <- zip [1..3] [2..4]]
λ: [(1,2),(2,1),(2,3),(3,2),(3,4),(4,3)]

CodePudding user response:

First, in your rule1, you don't need the list comprehension at all. The result of zip is already the list of tuples that you want:

rule1 = zip [1..3] [2..4]

For rule2, however, you can just use two nested generators, the second one derived from each element of the first, like this:

rule2 = [p | (a, b) <- zip [1..3] [2..4], p <- [(a, b), (b, a)]]

Or, alternatively, without destructuring the tuples, using swap instead:

rule2 = [p | p0 <- zip [1..3] [2..4], p <- [p0, swap p0]]
  • Related