Sunday, February 28, 2010

Re: dictionary functions: Is there a "magic" missing-attribute method/function?

Hi,

> I suspect you're reaching for the get() function
> which allows an optional 3rd parameter for a default

Thanks. But with the get() function the caller would have to know how
the values are computed and the computed value isn't added to the
dictionary. This doesn't make it a good solution for the intended use
cases.

One could of course define a wrapper function:

function! Get(dict, key, ...)
if !has_key(a:dict, a:key) && has_key(a:dict, '__Missing__')
call a:dict.__Missing__(a:key)
endif
return call('get', [a:dict, a:key] + a:000)
endf

let x = {}
function! x.__Missing__(n) dict
if a:n <= 1
let self[a:n] = a:n
else
let self[a:n] = Get(self, a:n - 2) + Get(self, a:n - 1)
endif
endfunction
echo map(range(0, 10), 'Get(x, v:val)')

Well, maybe that's sufficient. I just wasn't sure whether vim already
has such a functionality or not.

Regard,
Tom

--
You received this message from the "vim_use" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit http://www.vim.org/maillist.php

No comments: