Merge pull request #238 from prt2121/pt/haskell-7.10.1
[jackhill/mal.git] / matlab / Dict.m
CommitLineData
47699629
JM
1% Implement containers.Map like structure
2% This only applies to GNU Octave and will break in Matlab when
3% arbitrary string keys are used.
4classdef Dict < handle
5 properties
6 data
7 end
8 methods
9 function dict = Dict(keys, values)
10 dict.data = struct();
11
12 if nargin > 0
13 for i=1:length(keys)
14 dict.data.(keys{i}) = values{i};
15 end
16 end
17 end
18
19 function ret = subsasgn(dict, ind, val)
20 dict.data.(ind(1).subs{1}) = val;
21 ret = dict;
22 end
23 function ret = subsref(dict, ind)
24 if strcmp('.', ind(1).type)
25 % Function call
26 switch ind(1).subs
27 case 'isKey'
28 if numel(ind) > 1
29 ret = isfield(dict.data, ind(2).subs{1});
30 else
31 error('Dict:invalidArgs', ...
32 sprintf('''%s'' called with no arguments', ind(1).subs));
33 end
34 case 'keys'
35 ret = fieldnames(dict.data);
36 case 'values'
37 ret = {};
38 keys = fieldnames(dict.data);
39 for i=1:length(keys)
40 ret{end+1} = dict.data.(keys{i});
41 end
42 case 'remove'
43 if numel(ind) > 1
44 if numel(ind(2).subs) > 0
45 dict.data = rmfield(dict.data, ind(2).subs{1});
46 end
47 else
48 error('Dict:invalidArgs', ...
49 sprintf('''%s'' called with no arguments', ind(1).subs));
50 end
51 otherwise
52 error('Dict:notfound', ...
53 sprintf('''%s'' not found', ind(1).subs));
54 end
55 else
56 % Key lookup
57 ret = dict.data.(ind(1).subs{1});
58 end
59 end
60 end
61end