用haskell对递归添加到列表中



我想把我拥有的对列表添加到一个列表中。例如,如果我有对:

[(2,0),(4,5),(3,10)]

请注意,每对都是一个(值,索引(我想要:

[2,0,0,0,0,4,0,0,0,0,3]

到目前为止我有:

insert :: [(Int,Int)] -> Int -> [Int]
insert []                _ = [] 
insert ((x, y):xs) t
| t == y = x : (insert (xs) (t + 1))  
| otherwise = 0     : insert ([(x,y)]) (t + 1) 

我只得到

[2,0,0,0,0,0,4]

如有任何帮助,将不胜感激

代码的问题是,当otherwise = 0 : insert ([(x,y)]) (t + 1)完成时,列表的其余部分会被丢弃。剩余的xs丢失。

这里有两个递归:

  1. 列表中元素的递归
  2. 递归添加当前元素

所以,我重新编码添加了一个元素:

lst:: [(Int,Int)]
lst = [(2,0),(4,5),(3,10)]
insertOne :: (Int,Int) -> Int -> [Int] -> [Int]
insertOne (x, y) t out
| t == y = out ++ [x] 
| otherwise = insertOne (x,y) (t + 1) (out ++ [0])

还要添加所有元素:

insertList :: [(Int, Int)] -> [Int] -> [Int]
insertList [] target = target
insertList (x:xs) target =
insertList xs (insertOne x (length target) target)

如果输入列表是按索引排序的,那么这似乎是可行的。

insertList lst []  -- [2,0,0,0,0,4,0,0,0,0,3]

最新更新