how to do replacing-item in use nested list

前端 未结 1 1361
梦毁少年i
梦毁少年i 2021-01-28 14:36

replacing in nested list ??

for example

[[1 2][3 4] [5 1]]

to

[[99 2][3 4] [5 1]]

Can anybody please

相关标签:
1条回答
  • 2021-01-28 15:17

    Your question is somewhat underspecified. How do you want to decide which item gets changed?

    I'll suppose that you want to do it by indices, e.g. "0th item of 0th sublist". Then that's:

    to-report replace-subitem [index1 index2 lists value]
      let old-sublist item index1 lists
      report replace-item index1 lists (replace-item index2 old-sublist value)
    end
    
    observer> show replace-subitem 0 0 [[1 2] [3 4] [5 1]] 99
    observer: [[99 2] [3 4] [5 1]]
    

    You could also imagine doing the replacement according to other criteria. For example, suppose we want to change all of the occurrences of 1 in the first item of a sublist to 99. Then that's:

    to-report replace-first [old new the-list]
      if first the-list = old
        [ report replace-item 0 the-list new ]
      report the-list
    end
    
    to-report replace-firsts [old new lists]
      report map [replace-first old new ?] lists
    end
    
    observer> show replace-firsts 1 99 [[1 2] [3 4] [1 1]]
    observer: [[99 2] [3 4] [99 1]]
    

    A lot of other answers are possible as well, depending on exactly what problem you're trying to solve.

    0 讨论(0)
提交回复
热议问题