diff --git a/docs/Compiling_Joy.html b/docs/Compiling_Joy.html new file mode 100644 index 0000000..961e001 --- /dev/null +++ b/docs/Compiling_Joy.html @@ -0,0 +1,13543 @@ + + +
+from notebook_preamble import D, J, V, define
+V('23 sqr')
+How would we go about compiling this code (to Python for now)?
+The simplest thing would be to compose the functions from the library:
+ +dup, mul = D['dup'], D['mul']
+def sqr(stack, expression, dictionary):
+ return mul(*dup(stack, expression, dictionary))
+old_sqr = D['sqr']
+D['sqr'] = sqr
+V('23 sqr')
+It's simple to write a function to emit this kind of crude "compiled" code.
+ +def compile_joy(name, expression):
+ term, expression = expression
+ code = term +'(stack, expression, dictionary)'
+ format_ = '%s(*%s)'
+ while expression:
+ term, expression = expression
+ code = format_ % (term, code)
+ return '''\
+def %s(stack, expression, dictionary):
+ return %s
+''' % (name, code)
+
+
+def compile_joy_definition(defi):
+ return compile_joy(defi.name, defi.body)
+print compile_joy_definition(old_sqr)
+But what about literals?
+ +quoted == [unit] dip
+
+unit, dip = D['unit'], D['dip']
+# print compile_joy_definition(D['quoted'])
+# raises
+# TypeError: can only concatenate tuple (not "str") to tuple
+For a program like foo == bar baz 23 99 baq lerp barp we would want something like:
def foo(stack, expression, dictionary):
+ stack, expression, dictionary = baz(*bar(stack, expression, dictionary))
+ return barp(*lerp(*baq((99, (23, stack)), expression, dictionary)))
+You have to have a little discontinuity when going from a symbol to a literal, because you have to pick out the stack from the arguments to push the literal(s) onto it before you continue chaining function calls.
+ +Call-chaining results in code that does too much work. For functions that operate on stacks and only rearrange values, what I like to call "Yin Functions", we can do better.
+We can infer the stack effects of these functions (or "expressions" or "programs") automatically, and the stack effects completely define the semantics of the functions, so we can directly write out a two-line Python function for them. This is already implemented in the joy.utils.types.compile_() function.
from joy.utils.types import compile_, doc_from_stack_effect, infer_string
+from joy.library import SimpleFunctionWrapper
+stack_effects = infer_string('tuck over dup')
+Yin functions have only a single stack effect, they do not branch or loop.
+ +for fi, fo in stack_effects:
+ print doc_from_stack_effect(fi, fo)
+source = compile_('foo', stack_effects[0])
+All Yin functions can be described in Python as a tuple-unpacking (or "-destructuring") of the stack datastructure followed by building up the new stack structure.
+ +print source
+exec compile(source, '__main__', 'single')
+
+D['foo'] = SimpleFunctionWrapper(foo)
+V('23 18 foo')
+There are times when you're deriving a Joy program when you have a stack effect for a Yin function and you need to define it. For example, in the Ordered Binary Trees notebook there is a point where we must derive a function Ee:
[key old_value left right] new_value key [Tree-add] Ee
+------------------------------------------------------------
+ [key new_value left right]
+
+
+While it is not hard to come up with this function manually, there is no necessity. This function can be defined (in Python) directly from its stack effect:
+ + [a b c d] e a [f] Ee
+--------------------------
+ [a e c d]
+
+
+(I haven't yet implemented a simple interface for this yet. What follow is an exploration of how to do it.)
+ +from joy.parser import text_to_expression
+Ein = '[a b c d] e a [f]' # The terms should be reversed here but I don't realize that until later.
+Eout = '[a e c d]'
+E = '[%s] [%s]' % (Ein, Eout)
+
+print E
+(fi, (fo, _)) = text_to_expression(E)
+fi, fo
+Ein = '[a1 a2 a3 a4] a5 a6 a7'
+Eout = '[a1 a5 a3 a4]'
+E = '[%s] [%s]' % (Ein, Eout)
+
+print E
+(fi, (fo, _)) = text_to_expression(E)
+fi, fo
+def type_vars():
+ from joy.library import a1, a2, a3, a4, a5, a6, a7, s0, s1
+ return locals()
+
+tv = type_vars()
+tv
+from joy.utils.types import reify
+stack_effect = reify(tv, (fi, fo))
+print doc_from_stack_effect(*stack_effect)
+print stack_effect
+Almost, but what we really want is something like this:
+ +stack_effect = eval('(((a1, (a2, (a3, (a4, s1)))), (a5, (a6, (a7, s0)))), ((a1, (a5, (a3, (a4, s1)))), s0))', tv)
+Note the change of () to JoyStackType type variables.
print doc_from_stack_effect(*stack_effect)
+Now we can omit a3 and a4 if we like:
stack_effect = eval('(((a1, (a2, s1)), (a5, (a6, (a7, s0)))), ((a1, (a5, s1)), s0))', tv)
+The right and left parts of the ordered binary tree node are subsumed in the tail of the node's stack/list.
print doc_from_stack_effect(*stack_effect)
+source = compile_('Ee', stack_effect)
+print source
+Oops! The input stack is backwards...
+ +stack_effect = eval('((a7, (a6, (a5, ((a1, (a2, s1)), s0)))), ((a1, (a5, s1)), s0))', tv)
+print doc_from_stack_effect(*stack_effect)
+source = compile_('Ee', stack_effect)
+print source
+Compare:
+ + [key old_value left right] new_value key [Tree-add] Ee
+------------------------------------------------------------
+ [key new_value left right]
+
+eval(compile(source, '__main__', 'single'))
+D['Ee'] = SimpleFunctionWrapper(Ee)
+V('[a b c d] 1 2 [f] Ee')
+Consider the compiled code of dup:
def dup(stack):
+ (a1, s23) = stack
+ return (a1, (a1, s23))
+To compile sqr == dup mul we can compute the stack effect:
stack_effects = infer_string('dup mul')
+for fi, fo in stack_effects:
+ print doc_from_stack_effect(fi, fo)
+Then we would want something like this:
+ +def sqr(stack):
+ (n1, s23) = stack
+ n2 = mul(n1, n1)
+ return (n2, s23)
+How about...
+ +stack_effects = infer_string('mul mul sub')
+for fi, fo in stack_effects:
+ print doc_from_stack_effect(fi, fo)
+def foo(stack):
+ (n1, (n2, (n3, (n4, s23)))) = stack
+ n5 = mul(n1, n2)
+ n6 = mul(n5, n3)
+ n7 = sub(n6, n4)
+ return (n7, s23)
+
+
+# or
+
+def foo(stack):
+ (n1, (n2, (n3, (n4, s23)))) = stack
+ n5 = sub(mul(mul(n1, n2), n3), n4)
+ return (n5, s23)
+stack_effects = infer_string('tuck')
+for fi, fo in stack_effects:
+ print doc_from_stack_effect(fi, fo)
+First, we need a source of Python identifiers. I'm going to reuse Symbol class for this.
from joy.parser import Symbol
+def _names():
+ n = 0
+ while True:
+ yield Symbol('a' + str(n))
+ n += 1
+
+names = _names().next
+Now we need an object that represents a Yang function that accepts two args and return one result (we'll implement other kinds a little later.)
+ +class Foo(object):
+
+ def __init__(self, name):
+ self.name = name
+
+ def __call__(self, stack, expression, code):
+ in1, (in0, stack) = stack
+ out = names()
+ code.append(('call', out, self.name, (in0, in1)))
+ return (out, stack), expression, code
+A crude "interpreter" that translates expressions of args and Yin and Yang functions into a kind of simple dataflow graph.
+ +def I(stack, expression, code):
+ while expression:
+ term, expression = expression
+ if callable(term):
+ stack, expression, _ = term(stack, expression, code)
+ else:
+ stack = term, stack
+ code.append(('pop', term))
+
+ s = []
+ while stack:
+ term, stack = stack
+ s.insert(0, term)
+ if s:
+ code.append(('push',) + tuple(s))
+ return code
+Something to convert the graph into Python code.
+ +strtup = lambda a, b: '(%s, %s)' % (b, a)
+strstk = lambda rest: reduce(strtup, rest, 'stack')
+
+
+def code_gen(code):
+ coalesce_pops(code)
+ lines = []
+ for t in code:
+ tag, rest = t[0], t[1:]
+
+ if tag == 'pop':
+ lines.append(strstk(rest) + ' = stack')
+
+ elif tag == 'push':
+ lines.append('stack = ' + strstk(rest))
+
+ elif tag == 'call':
+ #out, name, in_ = rest
+ lines.append('%s = %s%s' % rest)
+
+ else:
+ raise ValueError(tag)
+
+ return '\n'.join(' ' + line for line in lines)
+
+
+def coalesce_pops(code):
+ index = [i for i, t in enumerate(code) if t[0] == 'pop']
+ for start, end in yield_groups(index):
+ code[start:end] = \
+ [tuple(['pop'] + [t for _, t in code[start:end][::-1]])]
+
+
+def yield_groups(index):
+ '''
+ Yield slice indices for each group of contiguous ints in the
+ index list.
+ '''
+ k = 0
+ for i, (a, b) in enumerate(zip(index, index[1:])):
+ if b - a > 1:
+ if k != i:
+ yield index[k], index[i] + 1
+ k = i + 1
+ if k < len(index):
+ yield index[k], index[-1] + 1
+
+
+def compile_yinyang(name, expression):
+ return '''\
+def %s(stack):
+%s
+ return stack
+''' % (name, code_gen(I((), expression, [])))
+A few functions to try it with...
+ +mul = Foo('mul')
+sub = Foo('sub')
+def import_yin():
+ from joy.utils.generated_library import *
+ return locals()
+
+yin_dict = {name: SimpleFunctionWrapper(func) for name, func in import_yin().iteritems()}
+
+yin_dict
+
+dup = yin_dict['dup']
+
+#def dup(stack, expression, code):
+# n, stack = stack
+# return (n, (n, stack)), expression
+... and there we are.
+ +print compile_yinyang('mul_', (names(), (names(), (mul, ()))))
+e = (names(), (dup, (mul, ())))
+print compile_yinyang('sqr', e)
+e = (names(), (dup, (names(), (sub, (mul, ())))))
+print compile_yinyang('foo', e)
+e = (names(), (names(), (mul, (dup, (sub, (dup, ()))))))
+print compile_yinyang('bar', e)
+e = (names(), (dup, (dup, (mul, (dup, (mul, (mul, ())))))))
+print compile_yinyang('to_the_fifth_power', e)
+from notebook_preamble import D, DefinitionWrapper, J, V, define
+Bird & Meertens
+ +scan in terms of a reduction.¶+ +Problem I. The reduction operator
+/of APL takes some binary operator⨁on its left and a vectorxof values on its right. The meaning of⨁/xforx = [a b ... z]is the valuea⨁b⨁...⨁z. For this to be well-defined in the absence of brackets, the operation⨁has to be associative. Now there is another operator\of APL calledscan. Its effect is closely related to reduction in that we have:
⨁\x = [a a⨁b a⨁b⨁c ... a⨁b⨁...⨁z]
+
+
++ +The problem is to find some definition of
+scanas a reduction. In other words, we have to find some functionfand an operator⨂so that
⨂\x = f(a)⨂f(b)⨂...⨂f(z)
+
+Ignoring the exact requirements (finding f and ⨂) can we implement scan as a hylomorphism in Joy?
Looking at the forms of hylomorphism, H3 is the one to use:
H3¶If the combiner and the generator both need to work on the current value then dup must be used, and the generator must produce one item instead of two (the b is instead the duplicate of a.)
H3 == [P] [pop c] [[G] dupdip] [dip F] genrec
+
+... a [G] dupdip [H3] dip F
+... a G a [H3] dip F
+... a′ a [H3] dip F
+... a′ H3 a F
+... a′ [G] dupdip [H3] dip F a F
+... a′ G a′ [H3] dip F a F
+... a″ a′ [H3] dip F a F
+... a″ H3 a′ F a F
+... a″ [G] dupdip [H3] dip F a′ F a F
+... a″ G a″ [H3] dip F a′ F a F
+... a‴ a″ [H3] dip F a′ F a F
+... a‴ H3 a″ F a′ F a F
+... a‴ pop c a″ F a′ F a F
+... c a″ F a′ F a F
+... d a′ F a F
+... d′ a F
+... d″
+
+We're building a list of values so this is an "anamorphism". (An anamorphism uses [] for c and swons for F.)
scan == [P] [pop []] [[G] dupdip] [dip swons] genrec
+
+
+Convert to ifte:
scan == [P] [pop []] [[G] dupdip [scan] dip swons] ifte
+
+On the recursive branch [G] dupdip doesn't cut it:
[1 2 3] [G] dupdip [scan] dip swons
+[1 2 3] G [1 2 3] [scan] dip swons
+
+first¶At this point, we want the copy of [1 2 3] to just be 1, so we use first.
scan == [P] [pop []] [[G] dupdip first] [dip swons] genrec
+
+[1 2 3] [G] dupdip first [scan] dip swons
+[1 2 3] G [1 2 3] first [scan] dip swons
+[1 2 3] G 1 [scan] dip swons
+
+G applies ⨁¶Now what does G have to do? Just apply ⨁ to the first two terms in the list.
[1 2 3] G
+[1 2 3] [⨁] infra
+[1 2 3] [+] infra
+[3 3]
+
+P¶Which tells us that the predicate [P] must guard against lists with less that two items in them:
P == size 1 <=
+
+Let's see what we've got so far:
+ +scan == [P ] [pop []] [[G] dupdip first] [dip swons] genrec
+scan == [size 1 <=] [pop []] [[[F] infra] dupdip first] [dip swons] genrec
+
+This works to a point, but it throws away the last term:
+ +J('[1 2 3] [size 1 <=] [pop []] [[[+] infra] dupdip first] [dip swons] genrec')
+Hmm... Let's take out the pop for a sec...
J('[1 2 3] [size 1 <=] [[]] [[[+] infra] dupdip first] [dip swons] genrec')
+That leaves the last item in our list, then it puts an empty list on the stack and swons's the new terms onto that. If we leave out that empty list, they will be swons'd onto that list that already has the last item.
J('[1 2 3] [size 1 <=] [] [[[+] infra] dupdip first] [dip swons] genrec')
+⨁¶So we have:
+ +[⨁] scan == [size 1 <=] [] [[[⨁] infra] dupdip first] [dip swons] genrec
+
+
+Trivially:
+ + == [size 1 <=] [] [[[⨁] infra] dupdip first] [dip swons] genrec
+ == [[[⨁] infra] dupdip first] [size 1 <=] [] roll< [dip swons] genrec
+ == [[⨁] infra] [dupdip first] cons [size 1 <=] [] roll< [dip swons] genrec
+ == [⨁] [infra] cons [dupdip first] cons [size 1 <=] [] roll< [dip swons] genrec
+
+
+And so:
+ +scan == [infra] cons [dupdip first] cons [size 1 <=] [] roll< [dip swons] genrec
+
+define('scan == [infra] cons [dupdip first] cons [size 1 <=] [] roll< [dip swons] genrec')
+J('[1 2 3 4] [+] scan')
+J('[1 2 3 4] [*] scan')
+J('[1 2 3 4 5 6 7] [neg +] scan')
++ +Define a line to be a sequence of characters not containing the newline character. It is easy to define a function
+Unlinesthat converts a non-empty sequence of lines into a sequence of characters by inserting newline characters between every two lines.Since
+Unlinesis injective, the functionLines, which converts a sequence of characters into a sequence of lines by splitting on newline characters, can be specified as the inverse ofUnlines.The problem, just as in Problem 1. is to find a definition by reduction of the function
+Lines.
Unlines = uncons ['\n' swap + +] step
+
+J('["hello" "world"] uncons ["\n" swap + +] step')
+Again ignoring the actual task let's just derive Lines:
"abc\nefg\nhij" Lines
+---------------------------
+ ["abc" "efg" "hij"]
+
+Instead of P == [size 1 <=] we want ["\n" in], and for the base-case of a string with no newlines in it we want to use unit:
Lines == ["\n" in] [unit] [R0] [dip swons] genrec
+Lines == ["\n" in] [unit] [R0 [Lines] dip swons] ifte
+
+Derive R0:
"a \n b" R0 [Lines] dip swons
+"a \n b" split-at-newline swap [Lines] dip swons
+"a " " b" swap [Lines] dip swons
+" b" "a " [Lines] dip swons
+" b" Lines "a " swons
+[" b"] "a " swons
+["a " " b"]
+
+So:
+ +R0 == split-at-newline swap
+
+Lines == ["\n" in] [unit] [split-at-newline swap] [dip swons] genrec
+
+This is all good and well, but in the paper many interesting laws and properties are discussed. Am I missing the point?
+ +0 [a b c d] [F] step == 0 [a b] [F] step 0 [c d] [F] step concat
+
+
+For associative function F and a "unit" element for that function, here represented by 0.
For functions that don't have a "unit" we can fake it (the example is given of infinity for the min(a, b) function.) We can also use:
safe_step == [size 1 <=] [] [uncons [F] step] ifte
+
+
+Or:
+ +safe_step == [pop size 1 <=] [pop] [[uncons] dip step] ifte
+
+ [a b c] [F] safe_step
+---------------------------
+ a [b c] [F] step
+
+
+To limit F to working on pairs of terms from its domain.
import sympy
+
+from joy.joy import run
+from joy.library import UnaryBuiltinWrapper
+from joy.utils.pretty_print import TracePrinter
+from joy.utils.stack import list_to_stack
+
+from notebook_preamble import D, J, V, define
+sympy.init_printing()
+The SymPy package provides a powerful and elegant "thunk" object that can take the place of a numeric value in calculations and "record" the operations performed on it.
+We can create some of these objects and put them on the Joy stack:
+ +stack = list_to_stack(sympy.symbols('c a b'))
+If we evaluate the quadratic program
over [[[neg] dupdip sqr 4] dipd * * - sqrt pm] dip 2 * [/] cons app2
+
+
+The SypPy Symbols will become the symbolic expression of the math operations. Unfortunately, the library sqrt function doesn't work with the SymPy objects:
viewer = TracePrinter()
+try:
+ run('over [[[neg] dupdip sqr 4] dipd * * - sqrt pm] dip 2 * [/] cons app2', stack, D, viewer.viewer)
+except Exception, e:
+ print e
+viewer.print_()
+We can pick out that first symbolic expression obect from the Joy stack:
+ +S, E = viewer.history[-1]
+q = S[0]
+q
+The Python math.sqrt() function causes the "can't convert expression to float" exception but sympy.sqrt() does not:
sympy.sqrt(q)
+sympy.sqrt¶This is easy to fix.
+ +D['sqrt'] = UnaryBuiltinWrapper(sympy.sqrt)
+Now it works just fine.
+ +(root1, (root2, _)) = run('over [[[neg] dupdip sqr 4] dipd * * - sqrt pm] dip 2 * [/] cons app2', stack, D)[0]
+root1
+root2
+At some point I will probably make an optional library of Joy wrappers for SymPy functions, and either load it automatically if SymPy installation is available or have a CLI switch or something. There's a huge amount of incredibly useful stuff and I don't see why Joy shouldn't expose another interface for using it. (As an example, the symbolic expressions can be "lambdafied" into very fast versions, i.e. a function that takes a, b, and c and computes the value of the root using just low-level fast code, bypassing Joy and Python. Also, Numpy, &c.)
Starting with the example from Partial Computation of Programs
+by Yoshihiko Futamura of a function to compute u to the kth power:
def F(u, k):
+ z = 1
+ while k != 0:
+ if odd(k):
+ z = z * u
+ k = k / 2
+ u = u * u
+ return z
+Partial evaluation with k = 5:
def F5(u):
+ z = 1 * u
+ u = u * u
+ u = u * u
+ z = z * u
+ return z
+Translate F(u, k) to Joy
u k 1 # z = 1
+ [pop] [Fw] while # the while statement
+ popopd # discard u k, "return" z
+
+What's Fw?
+ +u k z [pop odd] [Ft] [] ifte # the if statement
+ [2 //] dip # k = k / 2 floordiv
+ [sqr] dipd # u = u * u
+
+ [[sqr] dip 2 //] dip # We can merge last two lines.
+
+Helper function Ft (to compute z = z * u).
+ + u k z Ft
+---------------
+ u k u*z
+
+
+Ft == [over] dip *
+
+Putting it together:
+ +Ft == [over] dip *
+Fb == [[sqr] dip 2 //] dip
+Fw == [pop odd] [Ft] [] ifte Fb
+ F == 1 [pop] [Fw] while popopd
+
+define('odd == 2 %')
+define('Ft == [over] dip *')
+define('Fb == [[sqr] dip 2 //] dip')
+define('Fw == [pop odd] [Ft] [] ifte Fb')
+define('F == 1 [pop] [Fw] while popopd')
+Try it out:
+ +J('2 5 F')
+In order to elide the tests let's define special versions of while and ifte:
from joy.joy import joy
+from joy.library import FunctionWrapper
+from joy.parser import Symbol
+from joy.utils.stack import concat
+
+
+S_while = Symbol('while')
+
+
+@FunctionWrapper
+def while_(S, expression, dictionary):
+ '''[if] [body] while'''
+ (body, (if_, stack)) = S
+ if joy(stack, if_, dictionary)[0][0]:
+ expression = concat(body, (if_, (body, (S_while, expression))))
+ return stack, expression, dictionary
+
+
+@FunctionWrapper
+def ifte(stack, expression, dictionary):
+ '''[if] [then] [else] ifte'''
+ (else_, (then, (if_, stack))) = stack
+ if_res = joy(stack, if_, dictionary)[0][0]
+ quote = then if if_res else else_
+ expression = concat(quote, expression)
+ return (stack, expression, dictionary)
+
+
+D['ifte'] = ifte
+D['while'] = while_
+And with a SymPy symbol for the u argument:
stack = list_to_stack([5, sympy.symbols('u')])
+viewer = TracePrinter()
+try:
+ (result, _) = run('F', stack, D, viewer.viewer)[0]
+except Exception, e:
+ print e
+viewer.print_()
+result
+Let's try partial evaluation by hand and use a "stronger" thunk.
+Caret underscoring indicates terms that form thunks. When an arg is unavailable for a computation we just postpone it until the arg becomes available and in the meantime treat the pending computation as one unit.
+ + u 5 . F
+ u 5 . 1 [pop] [Fw] while popopd
+ u 5 1 . [pop] [Fw] while popopd
+ u 5 1 [pop] . [Fw] while popopd
+ u 5 1 [pop] [Fw] . while popopd
+ u 5 1 . Fw [pop] [Fw] while popopd
+ u 5 1 . [pop odd] [Ft] [] ifte Fb [pop] [Fw] while popopd
+ u 5 1 [pop odd] . [Ft] [] ifte Fb [pop] [Fw] while popopd
+ u 5 1 [pop odd] [Ft] . [] ifte Fb [pop] [Fw] while popopd
+ u 5 1 [pop odd] [Ft] [] . ifte Fb [pop] [Fw] while popopd
+ u 5 1 . Ft Fb [pop] [Fw] while popopd
+ u 5 1 . [over] dip * Fb [pop] [Fw] while popopd
+ u 5 1 [over] . dip * Fb [pop] [Fw] while popopd
+ u 5 . over 1 * Fb [pop] [Fw] while popopd
+ u 5 u . 1 * Fb [pop] [Fw] while popopd
+ u 5 u 1 . * Fb [pop] [Fw] while popopd
+ u 5 u . Fb [pop] [Fw] while popopd
+ u 5 u . [[sqr] dip 2 //] dip [pop] [Fw] while popopd
+ u 5 u [[sqr] dip 2 //] . dip [pop] [Fw] while popopd
+ u 5 . [sqr] dip 2 // u [pop] [Fw] while popopd
+ u 5 [sqr] . dip 2 // u [pop] [Fw] while popopd
+ u . sqr 5 2 // u [pop] [Fw] while popopd
+ u . dup mul 5 2 // u [pop] [Fw] while popopd
+ u dup * . 5 2 // u [pop] [Fw] while popopd
+ ^^^^^^^
+
+ u dup * 2 u [pop] [Fw] . while popopd
+ u dup * 2 u . Fw [pop] [Fw] while popopd
+ u dup * 2 u . [pop odd] [Ft] [] ifte Fb [pop] [Fw] while popopd
+ u dup * 2 u [pop odd] . [Ft] [] ifte Fb [pop] [Fw] while popopd
+ u dup * 2 u [pop odd] [Ft] . [] ifte Fb [pop] [Fw] while popopd
+ u dup * 2 u [pop odd] [Ft] [] . ifte Fb [pop] [Fw] while popopd
+ u dup * 2 u . Fb [pop] [Fw] while popopd
+ u dup * 2 u . [[sqr] dip 2 //] dip [pop] [Fw] while popopd
+ u dup * 2 u [[sqr] dip 2 //] . dip [pop] [Fw] while popopd
+ u dup * 2 . [sqr] dip 2 // u [pop] [Fw] while popopd
+ u dup * 2 [sqr] . dip 2 // u [pop] [Fw] while popopd
+ u dup * . sqr 2 2 // u [pop] [Fw] while popopd
+ u dup * . dup mul 2 2 // u [pop] [Fw] while popopd
+ u dup * dup * . 2 2 // u [pop] [Fw] while popopd
+ ^^^^^^^^^^^^^
+
+w/ K == u dup * dup *
K 1 u [pop] [Fw] . while popopd
+ K 1 u . Fw [pop] [Fw] while popopd
+ K 1 u . [pop odd] [Ft] [] ifte Fb [pop] [Fw] while popopd
+ K 1 u [pop odd] . [Ft] [] ifte Fb [pop] [Fw] while popopd
+ K 1 u [pop odd] [Ft] . [] ifte Fb [pop] [Fw] while popopd
+ K 1 u [pop odd] [Ft] [] . ifte Fb [pop] [Fw] while popopd
+ K 1 u . Ft Fb [pop] [Fw] while popopd
+ K 1 u . [over] dip * Fb [pop] [Fw] while popopd
+ K 1 u [over] . dip * Fb [pop] [Fw] while popopd
+ K 1 . over u * Fb [pop] [Fw] while popopd
+ K 1 K . u * Fb [pop] [Fw] while popopd
+ K 1 K u . * Fb [pop] [Fw] while popopd
+ K 1 K u * . Fb [pop] [Fw] while popopd
+ ^^^^^
+
+w/ L == K u *
K 1 L . Fb [pop] [Fw] while popopd
+ K 1 L . [[sqr] dip 2 //] dip [pop] [Fw] while popopd
+ K 1 L [[sqr] dip 2 //] . dip [pop] [Fw] while popopd
+ K 1 . [sqr] dip 2 // L [pop] [Fw] while popopd
+ K 1 [sqr] . dip 2 // L [pop] [Fw] while popopd
+ K . sqr 1 2 // L [pop] [Fw] while popopd
+ K . dup mul 1 2 // L [pop] [Fw] while popopd
+ K K . mul 1 2 // L [pop] [Fw] while popopd
+ K K * . 1 2 // L [pop] [Fw] while popopd
+ ^^^^^
+ K K * . 1 2 // L [pop] [Fw] while popopd
+ K K * 1 . 2 // L [pop] [Fw] while popopd
+ K K * 1 2 . // L [pop] [Fw] while popopd
+ K K * 0 . L [pop] [Fw] while popopd
+ K K * 0 L . [pop] [Fw] while popopd
+ K K * 0 L [pop] . [Fw] while popopd
+ K K * 0 L [pop] [Fw] . while popopd
+ ^^^^^
+ K K * 0 L . popopd
+ L .
+
+So:
+ +K == u dup * dup *
+L == K u *
+
+
+Our result "thunk" would be:
+ +u dup * dup * u *
+
+
+Mechanically, you could do:
+ +u dup * dup * u *
+u u [dup * dup *] dip *
+u dup [dup * dup *] dip *
+
+
+F5 == dup [dup * dup *] dip *
+
+
+But we can swap the two arguments to the final * to get all mentions of u to the left:
u u dup * dup * *
+
+
+
+Then de-duplicate "u":
+ +u dup dup * dup * *
+
+
+
+To arrive at a startlingly elegant form for F5:
+ +F5 == dup dup * dup * *
+
+stack = list_to_stack([sympy.symbols('u')])
+viewer = TracePrinter()
+try:
+ (result, _) = run('dup dup * dup * *', stack, D, viewer.viewer)[0]
+except Exception, e:
+ print e
+viewer.print_()
+result
+I'm not sure how to implement these kinds of thunks. I think you have to have support in the interpreter, or you have to modify all of the functions like dup to check for thunks in their inputs.
Working on the compiler, from this:
+ +dup dup * dup * *
+
+
+We can already generate:
+ +---------------------------------
+(a0, stack) = stack
+a1 = mul(a0, a0)
+a2 = mul(a1, a1)
+a3 = mul(a2, a0)
+stack = (a3, stack)
+---------------------------------
+
+
+This is pretty old stuff... (E.g. from 1999, M. Anton Ertl Compilation of Stack-Based Languages he goes a lot further for Forth.)
+ +by Arthur Nunes-Harwitt
+ + +def m(x, y): return x * y
+
+print m(2, 3)
+def m(x): return lambda y: x * y
+
+print m(2)(3)
+def m(x): return "lambda y: %(x)s * y" % locals()
+
+print m(2)
+print eval(m(2))(3)
+In Joy:
+ +m == [*] cons
+
+3 2 m i
+3 2 [*] cons i
+3 [2 *] i
+3 2 *
+6
+
+def p(n, b): # original
+ return 1 if n == 0 else b * p(n - 1, b)
+
+
+def p(n): # curried
+ return lambda b: 1 if n == 0 else b * p(n - 1, b)
+
+
+def p(n): # quoted
+ return "lambda b: 1 if %(n)s == 0 else b * p(%(n)s - 1, b)" % locals()
+
+
+print p(3)
+Original
+ +p == [0 =] [popop 1] [-- over] [dip *] genrec
+
+b n p
+b n [0 =] [popop 1] [-- over [p] dip *]
+
+b n -- over [p] dip *
+b n-1 over [p] dip *
+b n-1 b [p] dip *
+b n-1 p b *
+
+curried, quoted
+ + n p
+---------------------------------------------
+ [[n 0 =] [pop 1] [dup n --] [*] genrec]
+
+def p(n): # lambda lowered
+ return (
+ lambda b: 1
+ if n == 0 else
+ lambda b: b * p(n - 1, b)
+ )
+
+
+def p(n): # lambda lowered quoted
+ return (
+ "lambda b: 1"
+ if n == 0 else
+ "lambda b: b * p(%(n)s - 1, b)" % locals()
+ )
+
+print p(3)
+p == [0 =] [[pop 1]] [ [-- [dup] dip p *] cons ]ifte
+
+
+3 p
+3 [-- [dup] dip p *] cons
+[3 -- [dup] dip p *]
+
+def p(n): # expression lifted
+ if n == 0:
+ return lambda b: 1
+ f = p(n - 1)
+ return lambda b: b * f(b)
+
+
+print p(3)(2)
+def p(n): # quoted
+ if n == 0:
+ return "lambda b: 1"
+ f = p(n - 1)
+ return "lambda b: b * (%(f)s)(b)" % locals()
+
+print p(3)
+print eval(p(3))(2)
+p == [0 =] [pop [pop 1]] [-- p [dupdip *] cons] ifte
+
+
+3 p
+3 -- p [dupdip *] cons
+2 p [dupdip *] cons
+2 -- p [dupdip *] cons [dupdip *] cons
+1 p [dupdip *] cons [dupdip *] cons
+1 -- p [dupdip *] cons [dupdip *] cons [dupdip *] cons
+0 p [dupdip *] cons [dupdip *] cons [dupdip *] cons
+0 pop [pop 1] [dupdip *] cons [dupdip *] cons [dupdip *] cons
+[pop 1] [dupdip *] cons [dupdip *] cons [dupdip *] cons
+...
+[[[[pop 1] dupdip *] dupdip *] dupdip *]
+
+
+2 [[[[pop 1] dupdip *] dupdip *] dupdip *] i
+2 [[[pop 1] dupdip *] dupdip *] dupdip *
+2 [[pop 1] dupdip *] dupdip * 2 *
+2 [pop 1] dupdip * 2 * 2 *
+2 pop 1 2 * 2 * 2 *
+ 1 2 * 2 * 2 *
+
+
+
+p == [0 =] [pop [pop 1]] [-- p [dupdip *] cons] ifte
+p == [0 =] [pop [pop 1]] [-- [p] i [dupdip *] cons] ifte
+p == [0 =] [pop [pop 1]] [--] [i [dupdip *] cons] genrec
+
+define('p == [0 =] [pop [pop 1]] [--] [i [dupdip *] cons] genrec')
+J('3 p')
+V('2 [[[[pop 1] dupdip *] dupdip *] dupdip *] i')
+stack = list_to_stack([sympy.symbols('u')])
+(result, s) = run('p i', stack, D)[0]
+result
+From this:
+ +p == [0 =] [pop pop 1] [-- over] [dip *] genrec
+
+
+To this:
+ +p == [0 =] [pop [pop 1]] [--] [i [dupdip *] cons] genrec
+
+F():¶def odd(n): return n % 2
+
+
+def F(u, k):
+ z = 1
+ while k != 0:
+ if odd(k):
+ z = z * u
+ k = k / 2
+ u = u * u
+ return z
+
+F(2, 5)
+def F(k):
+ def _F(u, k=k):
+ z = 1
+ while k != 0:
+ if odd(k):
+ z = z * u
+ k = k / 2
+ u = u * u
+ return z
+ return _F
+
+F(5)(2)
+def F(k):
+ def _F(u, k=k):
+ if k == 0:
+ z = 1
+ else:
+ z = F(k / 2)(u)
+ z *= z
+ if odd(k):
+ z = z * u
+ return z
+ return _F
+
+F(5)(2)
+def F(k):
+ if k == 0:
+ z = lambda u: 1
+ else:
+ f = F(k / 2)
+ def z(u):
+ uu = f(u)
+ uu *= uu
+ return uu * u if odd(k) else uu
+ return z
+
+F(5)(2)
+def F(k):
+ if k == 0:
+ z = lambda u: 1
+ else:
+ f = F(k / 2)
+ if odd(k):
+ z = lambda u: (lambda fu, u: fu * fu * u)(f(u), u)
+ else:
+ z = lambda u: (lambda fu, u: fu * fu)(f(u), u)
+ return z
+
+F(5)(2)
+def F(k):
+ if k == 0:
+ z = "lambda u: 1"
+ else:
+ f = F(k / 2)
+ if odd(k):
+ z = "lambda u: (lambda fu, u: fu * fu * u)((%(f)s)(u), u)" % locals()
+ else:
+ z = "lambda u: (lambda fu, u: fu * fu)((%(f)s)(u), u)" % locals()
+ return z
+
+source = F(5)
+print source
+eval(source)(2)
+Hmm...
+ +for n in range(4):
+ print F(n)
+def F(k):
+ if k == 0:
+ z = "lambda u: 1"
+ elif k == 1:
+ z = "lambda u: u"
+ else:
+ f = F(k / 2)
+ if odd(k):
+ z = "lambda u: (lambda fu, u: fu * fu * u)((%(f)s)(u), u)" % locals()
+ else:
+ z = "lambda u: (lambda fu, u: fu * fu)((%(f)s)(u), u)" % locals()
+ return z
+
+source = F(5)
+print source
+eval(source)(2)
+for n in range(4):
+ print F(n)
+def F(k):
+ if k == 0:
+ z = "lambda u: 1"
+ elif k == 1:
+ z = "lambda u: u"
+ else:
+ m = k / 2
+ if odd(k):
+ if m == 0:
+ z = "lambda u: 1"
+ elif m == 1:
+ z = "lambda u: u * u * u"
+ else:
+ z = "lambda u: (lambda fu, u: fu * fu * u)((%s)(u), u)" % F(m)
+ else:
+ if m == 0:
+ z = "lambda u: 1"
+ elif m == 1:
+ z = "lambda u: u * u"
+ else:
+ z = "lambda u: (lambda u: u * u)((%s)(u))" % F(m)
+ return z
+
+source = F(5)
+print source
+eval(source)(2)
+def F(k):
+ if k == 0:
+ z = "lambda u: 1"
+ elif k == 1:
+ z = "lambda u: u"
+ else:
+ m = k / 2
+ if m == 0:
+ z = "lambda u: 1"
+
+ elif odd(k):
+ if m == 1:
+ z = "lambda u: u * u * u"
+ else:
+ z = "lambda u: (lambda fu, u: fu * fu * u)((%s)(u), u)" % F(m)
+ else:
+ if m == 1:
+ z = "lambda u: u * u"
+ else:
+ z = "lambda u: (lambda u: u * u)((%s)(u))" % F(m)
+ return z
+
+source = F(5)
+print source
+eval(source)(2)
+for n in range(7):
+ source = F(n)
+ print n, '%2i' % eval(source)(2), source
+So that gets pretty good, eh?
+But looking back at the definition in Joy, it doesn't seem easy to directly apply this technique to Joy code:
+ +Ft == [over] dip *
+Fb == [[sqr] dip 2 //] dip
+Fw == [pop odd] [Ft] [] ifte Fb
+ F == 1 [pop] [Fw] while popopd
+
+
+
+But a direct translation of the Python code..?
+ +F == [
+ [[0 =] [pop 1]]
+ [[1 =] []]
+ [_F.0]
+ ] cond
+
+_F.0 == dup 2 // [
+ [[0 =] [pop 1]]
+ [[pop odd] _F.1]
+ [_F.2]
+ ] cond
+
+_F.1 == [1 =] [pop [dup dup * *]] [popd F [dupdip over * *] cons] ifte
+_F.2 == [1 =] [pop [dup *]] [popd F [i dup *] cons] ifte
+
+
+
+Try it:
+ +5 F
+5 [ [[0 =] [pop 1]] [[1 =] []] [_F.0] ] cond
+5 _F.0
+5 dup 2 // [ [[0 =] [pop 1]] [[pop odd] _F.1] [_F.2] ] cond
+5 5 2 // [ [[0 =] [pop 1]] [[pop odd] _F.1] [_F.2] ] cond
+
+5 2 [ [[0 =] [pop 1]] [[pop odd] _F.1] [_F.2] ] cond
+5 2 _F.1
+5 2 [1 =] [popop [dup dup * *]] [popd F [dupdip over * *] cons] ifte
+5 2 popd F [dupdip over * *] cons
+ 2 F [dupdip over * *] cons
+
+2 F [dupdip over * *] cons
+
+2 F
+2 [ [[0 =] [pop 1]] [[1 =] []] [_F.0] ] cond
+2 _F.0
+2 dup 2 // [ [[0 =] [pop 1]] [[pop odd] _F.1] [_F.2] ] cond
+2 2 2 // [ [[0 =] [pop 1]] [[pop odd] _F.1] [_F.2] ] cond
+2 1 [ [[0 =] [pop 1]] [[pop odd] _F.1] [_F.2] ] cond
+2 1 _F.2
+2 1 [1 =] [popop [dup *]] [popd F [i dup *] cons] ifte
+2 1 popop [dup *]
+[dup *]
+
+
+2 F [dupdip over * *] cons
+[dup *] [dupdip over * *] cons
+[[dup *] dupdip over * *]
+
+
+And here it is in action:
+ +2 [[dup *] dupdip over * *] i
+2 [dup *] dupdip over * *
+2 dup * 2 over * *
+2 2 * 2 over * *
+4 2 over * *
+4 2 4 * *
+4 8 *
+32
+
+
+
+
+So, it works, but in this case the results of the partial evaluation are more elegant.
+ +hylomorphism():¶def hylomorphism(c, F, P, G):
+ '''Return a hylomorphism function H.'''
+
+ def H(a):
+ if P(a):
+ result = c
+ else:
+ b, aa = G(a)
+ result = F(b, H(aa))
+ return result
+
+ return H
+With abuse of syntax:
+ +def hylomorphism(c):
+ return lambda F: lambda P: lambda G: lambda a: (
+ if P(a):
+ result = c
+ else:
+ b, aa = G(a)
+ result = F(b)(H(aa))
+ return result
+ )
+def hylomorphism(c):
+ def r(a):
+ def rr(P):
+ if P(a):
+ return lambda F: lambda G: c
+ return lambda F: lambda G: (
+ b, aa = G(a)
+ return F(b)(H(aa))
+ )
+ return rr
+ return r
+def hylomorphism(c):
+ def r(a):
+ def rr(P):
+ def rrr(G):
+ if P(a):
+ return lambda F: c
+ b, aa = G(a)
+ H = hylomorphism(c)(aa)(P)(G)
+ return lambda F: F(b)(H(F))
+ return rrr
+ return rr
+ return r
+def hylomorphism(c):
+ def r(a):
+ def rr(P):
+ def rrr(G):
+ if P(a):
+ return "lambda F: %s" % (c,)
+ b, aa = G(a)
+ H = hylomorphism(c)(aa)(P)(G)
+ return "lambda F: F(%(b)s)((%(H)s)(F))" % locals()
+ return rrr
+ return rr
+ return r
+hylomorphism(0)(3)(lambda n: n == 0)(lambda n: (n-1, n-1))
+def F(a):
+ def _F(b):
+ print a, b
+ return a + b
+ return _F
+F(2)(3)
+eval(hylomorphism(0)(5)(lambda n: n == 0)(lambda n: (n-1, n-1)))(F)
+eval(hylomorphism([])(5)(lambda n: n == 0)(lambda n: (n-1, n-1)))(lambda a: lambda b: [a] + b)
+hylomorphism(0)([1, 2, 3])(lambda n: not n)(lambda n: (n[0], n[1:]))
+hylomorphism([])([1, 2, 3])(lambda n: not n)(lambda n: (n[1:], n[1:]))
+eval(hylomorphism([])([1, 2, 3])(lambda n: not n)(lambda n: (n[1:], n[1:])))(lambda a: lambda b: [a] + b)
+def hylomorphism(c):
+ return lambda a: lambda P: (
+ if P(a):
+ result = lambda F: lambda G: c
+ else:
+ result = lambda F: lambda G: (
+ b, aa = G(a)
+ return F(b)(H(aa))
+ )
+ return result
+ )
+def hylomorphism(c):
+ return lambda a: (
+ lambda F: lambda P: lambda G: c
+ if P(a) else
+ lambda F: lambda P: lambda G: (
+ b, aa = G(a)
+ return F(b)(H(aa))
+ )
+ )
+def hylomorphism(c):
+ return lambda a: lambda G: (
+ lambda F: lambda P: c
+ if P(a) else
+ b, aa = G(a)
+ lambda F: lambda P: F(b)(H(aa))
+ )
+