The Mathworks File Exchange repository has several hash or dictionary class implementations. Everything I examined uses parenthesis overloading to refer to keywords, for example.
d = Dict;
d('foo') = 'bar';
y = d('foo');
which seems like a reasonable interface. It would be preferable, however, if you want to easily have dictionaries that contain other dictionaries, use brackets {}instead of parentheses, since this circumvents the restriction on the type of MATLAB syntax (arbitrary, apparently), which does not have multiple parentheses, but multiple braces are allowed, i.e.
t{1}{2}{3} % is legal MATLAB
t(1)(2)(3) % is not legal MATLAB
So, if you want to easily insert dictionaries into dictionaries,
dict{'key1'}{'key2'}{'key3'}
Perl, , Python, , n-1 n , . subsref subsasgn , {}, (), .
, .
. ( . , , , .)
classdef TestBraces < handle
properties
% not a full hash table implementation, obviously
key
value
end
methods(Access = public)
function val = subsref(obj, ref)
% Re-implement dot referencing for methods.
if strcmp(ref(1).type, '.')
% User trying to access a method
% Methods access
if ismember(ref(1).subs, methods(obj))
if length(ref) > 1
% Call with args
val = obj.(ref(1).subs)(ref(2).subs{:});
else
% No args
val = obj.(ref.subs);
end
return;
end
% User trying to access something else.
error(['Reference to non-existant property or method ''' ref.subs '''']);
end
switch ref.type
case '()'
error('() indexing not supported.');
case '{}'
theKey = ref.subs{1};
if isequal(obj.key, theKey)
val = obj.value;
else
error('key %s not found', theKey);
end
otherwise
error('Should never happen')
end
end
function obj = subsasgn(obj, ref, value)
%Dict/SUBSASGN Subscript assignment for Dict objects.
%
% See also: Dict
%
if ~strcmp(ref.type,'{}')
error('() and dot indexing for assignment not supported.');
end
% Vectorized calls not supported
if length(ref.subs) > 1
error('Dict only supports storing key/value pairs one at a time.');
end
theKey = ref.subs{1};
obj.key = theKey;
obj.value = value;
end % subsasgn
end
end
, :
t = TestBraces;
t{'foo'} = 'bar'
( , t.) , subsasgn .
(subsref ):
t{'foo'}
??? Error using ==> subsref
Too many output arguments.
, subsref , , , MATLAB, .
() , , () {}. ( , , .)
, , , , , , .