Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flatten a nested list in Vim script?

I found some Vim list functions can not work as I thought. For example:

let list0 = [1, [1, 2]]
echo count(list0, 1)

It returns 1, but I want it returns 2. So I think those functions can not deep into nested lists, only work on first level.

I think here I should expand nested list into a normal list like this:

list0 = [1, 1, 2]

How to flatten a nested list?

like image 796
stardiviner Avatar asked Sep 17 '25 00:09

stardiviner


1 Answers

" Code from bairui@#vim.freenode
" https://gist.github.com/3322468
function! Flatten(list)
  let val = []
  for elem in a:list
    if type(elem) == type([])
      call extend(val, Flatten(elem))
    else
      call add(val, elem)
    endif
    unlet elem
  endfor
  return val
endfunction

Here unlet elem is necessary. Because the elem variable is changing, it is a list item, or a list, and VimL does not support assign a list item to a list, and vice versa.

like image 160
stardiviner Avatar answered Sep 19 '25 16:09

stardiviner