我有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"]
感谢, 米。
答案 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"]