对不起,我刚刚开始学习Haskell。我不明白如何在每个子列表中附加一个元组。
我当前的列表是:
[[("String", "String", 2.0)],[("String", "String", 2.0),("String", "String", 2.0)]]
我想在每个子列表中添加一个元组,所以我的新列表是:
[[("String", "String", 2.0),("String","String",0.0)],[("String", "String", 2.0),("String", "String", 2.0),("String","String",0.0)]]
我正在尝试编写一个函数,但是它一直在给我一个错误
append :: a -> [a] -> [a]
append i (x:xs) = x : append i xs
append i [] = i : []
然后我这样做:
map append ("String","String",0.0)
这给了我很多错误,例如不正确的“类型匹配”。我不确定如何在Haskell中添加内容。
答案 0 :(得分:2)
[[("String", "String", 2.0)],[("String", "String", 2.0),("String", "String", 2.0)]]
的类型是Fractional t => [[(String, String, t)]]
,或者为了简化[[(String, String, Double)]]
。
因此,为了将元素追加到每个嵌套列表中,我们需要有一个函数(String, String, Double) -> [[(String, String, Double)]] -> [[(String, String, Double)]]
。换句话说,a -> [[a]] -> [[a]]
:
append :: a -> [[a]] -> [[a]]
append x xs = map (\xss -> xss ++ [x]) xs
最后
> append ("String","String",0.0) [[("String", "String", 2.0)],[("String", "String", 2.0),("String", "String", 2.0)]]
[[("String","String",2.0),("String","String",0.0)],[("String","String",2.0),("String","String",2.0),("String","String",0.0)]]
请注意,将元素添加到列表的末尾是O(n),因此您可以考虑将其添加到开头:
append' :: a -> [[a]] -> [[a]]
append' x = map ((:) x)