For now, there is no way to define new functions from within the Joy language. All functions (and the interpreter) all accept and return a dictionary parameter (in addition to the stack and expression) so that we can implement e.g. a function that adds new functions to the dictionary. However, there's no function that does that. Adding a new function to the dictionary is a meta-interpreter action, you have to do it in Python, not Joy.
from notebook_preamble import D, J, V
V('[23 18] average')
size
with a Python version¶Both sum
and size
each convert a sequence to a single value.
sum == 0 swap [+] step
size == 0 swap [pop ++] step
An efficient sum
function is already in the library. But for size
we can use a “compiled” version hand-written in Python to speed up evaluation and make the trace more readable.
from joy.library import SimpleFunctionWrapper
from joy.utils.stack import iter_stack
@SimpleFunctionWrapper
def size(stack):
'''Return the size of the sequence on the stack.'''
sequence, stack = stack
n = 0
for _ in iter_stack(sequence):
n += 1
return n, stack
Now we replace the old version in the dictionary with the new version, and re-evaluate the expression.
D['size'] = size
You can see that size
now executes in a single step.
V('[23 18] average')