Example (1)
>
|
m := module() local ModuleApply;
ModuleApply := proc()
print("m called with args: ", [args]);
end proc;
end module;
|
| (1) |
| (2) |
Example (2)
In this example, we create a generic function that can deal with objects that export an Evalf function.
>
|
MyEvalf := proc(f)
if type(f,function) and type(op(0,f),`module`(Evalf)) then
op(0,f):-Evalf(op(f));
else
error "cannot evaluate %1", f;
end if;
end proc;
|
| (3) |
Now, create an object that returns unevaluated under certain conditions. Teach the object how to behave in specific environments (like the environment of MyEvalf).
>
|
Sine := module() local ModuleApply; export Evalf;
ModuleApply := proc(x)
if type(x,float) then
sin(x);
else
'Sine'(x);
end if;
end proc;
Evalf := proc(x)
`evalf/sin`(x);
end proc;
end module;
|
| (4) |
With floating-point data, a number is returned, otherwise Sine returns unevaluated. This is achieved by calling the ModuleApply.
Applying MyEvalf to the unevaluated response causes MyEvalf to dispatch to the object itself to compute the value.
The Cache module implements a ModuleApply function. Using Cache as a command creates a new cache table. For example: