1
votes

please can you help me with following?

I have 2 arrays which I need to merge into one Data array. The code below does the merge, but it creates a cartesian...

I would like to have following on output:

DataXY {var1 = "x1", var2 = "y1"},
DataXY {var1 = "x2", var2 = "y2"},
DataXY {var1 = "x3", var2 = "y3"}

---code

data  DataXY = DataXY {
   var1 :: String,
   var2 :: String
} deriving (Eq, Show)

parse ::  [DataXY]
parse = x
    where
        x = [DataXY v1 v2 | v1 <- arr1, v2 <- arr2]
            where
                arr1 = ["x1", "x2", "x3"]
                arr2 = ["y1", "y2", "y3"]

thanks, m.

2

2 Answers

9
votes

zipWith is what you want here

parse :: [DataXY]
parse = zipWith DataXY arr1 arr2
   where arr1 = ["x1", "x2", "x3"]
         arr2 = ["y1", "y2", "y3"]
4
votes

Zip the two lists to avoid the cartesian product:

parse ::  [DataXY]
parse = x
    where
        x = [DataXY v1 v2 | (v1,v2)  <- zip arr1 arr2]
            where
                arr1 = ["x1", "x2", "x3"]
                arr2 = ["y1", "y2", "y3"]

With GHC you can enable parallel list comprehension with -XParallelListComp and write

parse ::  [DataXY]
parse = x
    where
        x = [DataXY v1 v2 | v1 <- arr1 | v2 <- arr2 ]
            where
                arr1 = ["x1", "x2", "x3"]
                arr2 = ["y1", "y2", "y3"]