【发布时间】:2021-04-30 01:14:39
【问题描述】:
我有一些这样的代码:
data Set = Set String [Int]
deriving (Show, Read)
getArr :: Set -> [Int]
getArr (Set _ arr) = arr
我的目标是编写一个将值列表输入到元组中的函数。
例如:
数据 -
"One" [1], "Two" [2], "Three" [3]
输出:"One" [0, 1], "Two" [1,2], "Three" [3,3],输入为 [0, 1, 3]
我对此的一般方法是递归地遍历数据,同时使用 : 将其添加到第一个索引中。
我试图做类似的事情:
addToSet :: [Set] -> [Int] -> [Set]
addToSet [] [] = []
addToSet (x:xs) (y:ys) = (getArr x : y) ++ addToSet xs
但我收到一条错误消息:
Couldn't match type ‘[Int]’ with ‘Set’
Expected type: [Set]
Actual type: [[Int]]```
【问题讨论】:
-
这里发生了很多事情 - 首先
get Arr x : y将导致Int-list(getArr的结果)被添加到 [Int]`(y) - 然后结果(它应该是什么)与[Int] -> [Set]连接(你只将xs部分应用到addToSet)......另外:你能做一个更好的例子(输入到addToSet和预期输出)?您上半场的例子似乎与下半场完全无关
标签: haskell