【问题标题】:recursively adding to list with pairs haskell用对haskell递归添加到列表
【发布时间】:2022-10-13 04:33:32
【问题描述】:

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

[(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]

任何帮助,将不胜感激

【问题讨论】:

  • 这看起来像您最近提出的一个非常相似的问题。
  • @FrancisKing 是的,但它包含了该问题的答案。我认为这就是我们要求人们做的事情:如果您在解决方案的过程中遇到了一个新问题,请提出一个新问题。

标签: haskell


【解决方案1】:

代码的问题在于,当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]
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 2019-11-16
    相关资源
    最近更新 更多