1

请你能帮我跟随吗?

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

我想在输出上有以下内容:

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

谢谢,米。

4

2 回答 2

9

zipWith是你想要的

parse :: [DataXY]
parse = zipWith DataXY arr1 arr2
   where arr1 = ["x1", "x2", "x3"]
         arr2 = ["y1", "y2", "y3"]
于 2013-10-29T15:14:50.953 回答
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 启用并行列表理解并编写

parse ::  [DataXY]
parse = x
    where
        x = [DataXY v1 v2 | v1 <- arr1 | v2 <- arr2 ]
            where
                arr1 = ["x1", "x2", "x3"]
                arr2 = ["y1", "y2", "y3"]
于 2013-10-29T15:14:51.143 回答