comparison Dictionary.m @ 40:54d3ab296ba0

Added Dictionary class. Added string conversions for a bunch of types. Deprecated some replaced functions.
author Jonatan Werpers <jonatan@werpers.com>
date Mon, 12 Oct 2015 10:38:53 +0200
parents
children 8298734b1938
comparison
equal deleted inserted replaced
39:7249f105e67b 40:54d3ab296ba0
1 % TODO
2 % Documentation
3 % Should the storage be done in some other way?
4 % Cell array as keys?
5 % Some possibility to load and save to a matfile?
6 % May be load and save from outside is enough.
7 % Get and set functions called by subsref and subsasgn?
8 % Unit tests.
9
10
11 classdef Dictionary
12 properties
13 store
14 end
15
16 methods
17 function obj = Dictionary()
18 obj.store = struct();
19 end
20
21 function s = getStore(obj)
22 s = obj.store;
23 end
24
25 function display(obj)
26 if length(fieldnames(obj.store)) == 0
27 fprintf('%s is an empty Dictionary\n',inputname(1));
28 return
29 end
30
31 lineformat = [inputname(1) '(%s) = %s\n'];
32
33 display_impl(obj.store,'');
34
35 function display_impl(s, path)
36 if ~isstruct(s)
37 fprintf(lineformat,path(3:end), value2str(s));
38 % fprintf(') = %s\n', value2str(s));
39 % fprintf('%s(', objName);
40 return
41 end
42
43 fn = fieldnames(s);
44
45 for i = 1:length(fn)
46 display_impl(s.(fn{i}), [path ', ' fn{i}(2:end)]);
47 end
48
49 end
50
51 function str = value2str(val)
52 if isnumeric(val) || ischar(val)
53 str = mat2str(val);
54 else
55 str = class(val);
56 end
57 end
58 end
59
60 % B = obj(i)
61 function B = subsref(obj,S)
62 switch S.type
63 case '()'
64 Sf = obj.subs2dotSubs(S);
65 try
66 B = subsref(obj.store,Sf);
67 catch ME
68 if strcmp(ME.identifier,'MATLAB:nonExistentField')
69 error('Reference to non-existent entry %s',toString(S.subs));
70 else
71 throw(ME);
72 end
73 end
74 otherwise
75 error('Unsupported indexing operator: %s',S.type);
76 end
77 end
78
79 % A(i) = B
80 function obj = subsasgn(obj,S,B);
81 switch S.type
82 case '()'
83 Sf = obj.subs2dotSubs(S);
84 obj.store = subsasgn(obj.store,Sf,B);
85 otherwise
86 error('Unsupported indexing operator: %s',S.type);
87 end
88 end
89
90 function Sf = subs2dotSubs(obj,S)
91 for i = 1:length(S.subs)
92 Sf(i).type = '.';
93 Sf(i).subs = obj.getFieldname(S.subs{i});
94 end
95 end
96
97 % Should probably use mat2str with some kind of normalization to make all variables valied fieldname
98 % and make it possible to recover the value
99 function fName = getFieldname(obj, val)
100 if isnumeric(val)
101 valStr = num2str(val);
102 elseif ischar(val)
103 valStr = val;
104 else
105 error('Dont know what to do with val!');
106 end
107 fName = sprintf('f%s',valStr);
108 end
109 end
110 end