How to flatten a nested list in Vim script?

expand, list, nested, vim

Solution

" 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.

Problem

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?

Original source