1

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!

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

If the string is not fixed at a length of 2 characters, it may be beneficial to: zip [1..] "ab"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.