Thursday, February 5, 2009

Ch6, Ex13

declare
fun {NewDictionary}
L={NewCell nil}
proc {Put K V}
{Remove K}
L:=(K#V)|@L
end
fun {Get K}
fun {Iter Xs}
case Xs of
(Key#Val)|Xr andthen K==Key then Val
[] (Key#Val)|Xr then {Iter Xr}
[] nil then raise keyNotFound end
end
end
in
{Iter @L}
end
fun {CondGet K A}
try {Get K}
catch X then A
end
end
fun {Member K}
fun {Iter Xs}
case Xs of
(Key#Val)|Xr andthen K==Key then true
[] (Key#Val)|Xr then {Iter Xr}
[] nil then false
end
end
in
{Iter @L}
end
proc {Remove K}
fun {Iter Xs}
case Xs of
(Key#Val)|Xr andthen K==Key then {Iter Xr}
[] (Key#Val)|Xr then (Key#Val)|{Iter Xr}
[] nil then nil
end
end
in
L:={Iter @L}
end
fun {Keys}
proc {Iter Xs ?R}
case Xs of
(Key#Val)|Xr then Y in
R=Key|Y
{Iter Xr Y}
[] nil then R=nil
end
end
in
{Iter @L $}
end
%for debugging only
fun {ListContent}
@L
end
in
dict(put:Put get:Get condGet:CondGet member:Member
remove:Remove list:ListContent keys:Keys)
end

Note: We can not support Dictionary.toRecord operation for this dictionary as record feature can only be atom, bool or int and in this dictionary keys can be any value.

No comments:

Post a Comment