Home > Software engineering >  Haskell: List comprehension unique char from string
Haskell: List comprehension unique char from string

Time:10-15

Here is my current list comprehension: [((a,b),a 1) | a <- [1,2], b <- "ab"]

Current output: [((1,'a'),2),((1,'b'),2),((2,'a'),3),((2,'b'),3)]

Intended output: [((1,'a'),2),((2,'b'),3)]

How can I edit my list comprehension to achieve the intended output?

Thanks in advance!

CodePudding user response:

Having two generators produces all possible combinations of the items. You want a single generator produced by zipping the two lists together.

[((a,b), a 1) | (a, b) <- zip [1,2] "ab"]

You can also write

[(t, a 1) | t@(a, _) <- zip [1,2] "ab"]

or

[(t, fst t   1) | t <- zip [1,2] "ab"]

because you don't care about b except to reconstruct the tuple you just unpacked from zip.

GHC also provides an extension, ParallelListComp, to zip the generators implicitly.

> :set -XParallelListComp
> [((a,b), a 1) | a <- [1,2] | b <- "ab"]

Note the use of | instead of , to separate the two generators.

  • Related