0

我需要一个带有 API 的容器,例如:

addKeyValuePair(containerRef, [key, value])
searchByKey(containerRef, key) #that would return NULL or `value`

如何在 Maple (15) 中创建这样的东西?

4

1 回答 1

1

You might just want usual indexing into a table. Note that previously unassigned name Y below becomes a table just by virtue of assigning to some indexed entry Y[a].

restart:
Y[a]:=211:

Y[a];
                          211

Y[b];
                          Y[b]

assigned(Y[a]);
                          true

assigned(Y[b]);
                         false

eval(Y);
                      table([a = 211])

Having said all that, it's only a small bit of wrapping to get the functionality you've described, where accessing Y[b] returns NULL when Y[b] is not yet assigned, etc.

You can of customize (or remove) the error checking and restriction that key be of type symbol, as Maple allows a table to be indexed more generally.

restart:

addKeyValuePair:=proc(containerRef::{indexed,symbol}, L::list)
  if nops(L) <> 2 then
    error "expecting list with two entries"; end if;
  if not type(L[1], symbol) then
    error "expecting list with symbol as first entry"; end if;
  containerRef[L[1]]:=L[2];
  NULL;
end proc:

searchByKey:=proc(containerRef::{indexed,symbol}, key::name)
  if assigned(containerRef[key]) then
    containerRef[key];
  else
    NULL;
  end if;
end proc:

addKeyValuePair( Y, [a, 4.5] );

searchByKey( Y, a );
                          4.5

searchByKey( Y, b );

searchByKey( Q, b );

addKeyValuePair( Y, [a, 211] );

searchByKey( Y, a );
                          211

addKeyValuePair( Y, [c] );
Error, (in addKeyValuePair) expecting list with two entries

addKeyValuePair( Y, [2.34, 211] );
Error, (in addKeyValuePair) expecting list with symbol as first entry

A table is a mutable data structure. It is of type last_name_eval and in consequence it (effectively) gets passed "by reference" as argument to a procedure call.

于 2012-12-21T08:42:30.843 回答