Reputation: 4219
I've been looking some time now and I couldn't find how to do this. Suppose I have two lists, I want to return a new list that is the same as the result of zip
but without the duples, e.g., given [1,2,3]
and [4,5,6]
the result would be [1,4,2,5,3,6]
. I would do it like (suppossing the compiler don't generate an error):
myFunc xs ys = [x,y|(x,y) <- zip xs ys]
PS: Have to do it with list comprehension.
Could you give some thoughts about it?
Upvotes: 0
Views: 2855
Reputation: 245
func a b = concat (map ( \(x,y) -> [x,y] ) (zip a b))
Do you mean something like this ?
Upvotes: 1
Reputation: 153152
This can also be conveniently done without extensions:
myFunc xs ys = [x | pairs <- transpose [xs, ys], x <- pairs]
This doesn't throw away elements as Thomas M. DuBuisson's answer does; e.g. myFunc [] [1]
will be [1]
, not []
. Whether that's desirable or not depends on your needs, of course.
But even simpler is not to use list comprehensions at all, so that you don't need to name the intermediary pairs
.
myFunc xs ys = concat (transpose [xs, ys])
Upvotes: 2
Reputation: 64740
You probably want -XParallelListComp
which is a syntactic sugar for zip. Other than that sugar the solution matches what has already been suggested:
{-# LANGUAGE ParallelListComp #-}
xs = [1..3]
ys = [4..6]
ls = concat [ [x,y] | x <- xs | y <- ys ]
With a result of:
*Main> ls
[1,4,2,5,3,6]
Upvotes: 2