haskell:将两个数组合并为一个Data数组

时间:2013-10-29 15:04:56

标签: haskell

你可以帮我跟进吗?

我有2个数组,我需要合并到一个数据数组中。下面的代码执行合并,但它创建了一个笛卡儿...

我想关注输出:

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

---代码

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"]

感谢, 米。

2 个答案:

答案 0 :(得分:10)

zipWith就是你想要的

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

答案 1 :(得分:4)

压缩两个列表以避免使用笛卡尔积:

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

使用GHC,您可以使用-XParallelListComp和write

启用并行列表理解
parse ::  [DataXY]
parse = x
    where
        x = [DataXY v1 v2 | v1 <- arr1 | v2 <- arr2 ]
            where
                arr1 = ["x1", "x2", "x3"]
                arr2 = ["y1", "y2", "y3"]