1 # -*- coding: utf-8 -*-
3 # Copyright © 2014, 2015, 2017, 2018 Simon Forman
5 # This file is part of Thun
7 # Thun is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # Thun is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Thun. If not see <http://www.gnu.org/licenses/>.
21 This module contains the Joy function infrastructure and a library of
22 functions. Its main export is a Python function initialize() that
23 returns a dictionary of Joy functions suitable for use with the joy()
26 from inspect import getdoc
27 from functools import wraps
30 from .parser import text_to_expression, Symbol
31 from .utils.stack import list_to_stack, iter_stack, pick, concat
32 from .utils.brutal_hackery import rename_code_object
38 def inscribe(function):
39 '''A decorator to inscribe functions into the default dictionary.'''
40 _dictionary[function.name] = function
45 '''Return a dictionary of Joy functions for use with joy().'''
46 return _dictionary.copy()
55 ('mod', ['%', 'rem', 'remainder', 'modulus']),
58 ('getitem', ['pick', 'at']),
69 ('rolldown', ['roll<']),
70 ('rollup', ['roll>']),
75 def add_aliases(D, A):
77 Given a dict and a iterable of (name, [alias, ...]) pairs, create
78 additional entries in the dict mapping each alias to the named function
79 if it's in the dict. Aliases for functions not in the dict are ignored.
81 for name, aliases in A:
92 third == rest rest first
94 product == 1 swap [*] step
96 swoncat == swap concat
97 flatten == [] swap [concat] step
101 enstacken == stack [clear] dip
102 disenstacken == ? [uncons ?] loop pop
104 dinfrirst == dip infra first
105 nullary == [stack] dinfrirst
106 unary == [stack [pop] dip] dinfrirst
107 binary == [stack [popop] dip] dinfrirst
108 ternary == [stack [popop pop] dip] dinfrirst
112 size == 0 swap [pop ++] step
113 cleave == [i] app2 [popd] dip
114 average == [sum 1.0 *] [size] cleave /
115 gcd == 1 [tuck modulus dup 0 >] loop pop
116 least_fraction == dup [gcd] infra [div] concat map
117 *fraction == [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons
118 *fraction0 == concat [[swap] dip * [*] dip] infra
119 down_to_zero == [0 >] [dup --] while
120 range_to_zero == unit [down_to_zero] infra
121 anamorphism == [pop []] swap [dip swons] genrec
122 range == [0 <=] [1 - dup] anamorphism
123 while == swap [nullary] cons dup dipd concat loop
125 primrec == [i] genrec
126 step_zero == 0 roll> step
127 codireco == cons dip rest cons
128 make_generator == [codireco] ccons
133 ##z-down == [] swap uncons swap
134 ##z-up == swons swap shunt
135 ##z-right == [swons] cons dip uncons swap
136 ##z-left == swons [uncons swap] dip swap
139 ##divisor == popop 2 *
141 ##radical == swap dup * rollup * 4 * - sqrt
144 ##q0 == [[divisor] [minusb] [radical]] pam
145 ##q1 == [[root1] [root2]] pam
146 ##quadratic == [q0] ternary i [q1] ternary
150 ##PE1.1 == + dup [+] dip
151 ##PE1.2 == dup [3 & PE1.1] dip 2 >>
152 ##PE1.3 == 14811 swap [PE1.2] times pop
153 ##PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop
155 #PE1.2 == [PE1.1] step
156 #PE1 == 0 0 66 [[3 2 1 3 1 2 3] PE1.2] times [3 2 1 3] PE1.2 pop
160 def FunctionWrapper(f):
161 '''Set name attribute.'''
163 raise ValueError('Function %s must have doc string.' % f.__name__)
164 f.name = f.__name__.rstrip('_') # Don't shadow builtins.
168 def SimpleFunctionWrapper(f):
170 Wrap functions that take and return just a stack.
174 @rename_code_object(f.__name__)
175 def inner(stack, expression, dictionary):
176 return f(stack), expression, dictionary
180 def BinaryBuiltinWrapper(f):
182 Wrap functions that take two arguments and return a single result.
186 @rename_code_object(f.__name__)
187 def inner(stack, expression, dictionary):
188 (a, (b, stack)) = stack
190 return (result, stack), expression, dictionary
194 def UnaryBuiltinWrapper(f):
196 Wrap functions that take one argument and return a single result.
200 @rename_code_object(f.__name__)
201 def inner(stack, expression, dictionary):
204 return (result, stack), expression, dictionary
208 class DefinitionWrapper(object):
210 Provide implementation of defined functions, and some helper methods.
213 def __init__(self, name, body_text, doc=None):
214 self.name = self.__name__ = name
215 self.body = text_to_expression(body_text)
216 self._body = tuple(iter_stack(self.body))
217 self.__doc__ = doc or body_text
219 def __call__(self, stack, expression, dictionary):
220 expression = list_to_stack(self._body, expression)
221 return stack, expression, dictionary
224 def parse_definition(class_, defi):
226 Given some text describing a Joy function definition parse it and
227 return a DefinitionWrapper.
229 name, proper, body_text = (n.strip() for n in defi.partition('=='))
231 raise ValueError('Definition %r failed' % (defi,))
232 return class_(name, body_text)
235 def add_definitions(class_, defs, dictionary):
237 Scan multi-line string defs for definitions and add them to the
240 for definition in _text_to_defs(defs):
241 class_.add_def(definition, dictionary)
244 def add_def(class_, definition, dictionary):
246 Add the definition to the dictionary.
248 F = class_.parse_definition(definition)
249 dictionary[F.name] = F
252 def _text_to_defs(text):
253 return (line.strip() for line in text.splitlines() if '==' in line)
262 @SimpleFunctionWrapper
264 '''Parse the string on the stack to a Joy expression.'''
266 expression = text_to_expression(text)
267 return expression, stack
271 @SimpleFunctionWrapper
279 ((head, tail), stack) = stack
284 @SimpleFunctionWrapper
292 ((head, tail), stack) = stack
297 @SimpleFunctionWrapper
302 getitem == drop first
304 Expects an integer and a quote on the stack and returns the item at the
305 nth position in the quote counting from 0.
309 -------------------------
313 n, (Q, stack) = stack
314 return pick(Q, n), stack
318 @SimpleFunctionWrapper
325 Expects an integer and a quote on the stack and returns the quote with
326 n items removed off the top.
330 ----------------------
334 n, (Q, stack) = stack
345 @SimpleFunctionWrapper
348 Expects an integer and a quote on the stack and returns the quote with
349 just the top n items in reverse order (because that's easier and you can
350 use reverse if needed.)
354 ----------------------
358 n, (Q, stack) = stack
371 @SimpleFunctionWrapper
374 Use a Boolean value to select one of two items.
378 ----------------------
383 ---------------------
386 Currently Python semantics are used to evaluate the "truthiness" of the
387 Boolean value (so empty string, zero, etc. are counted as false, etc.)
389 (if_, (then, (else_, stack))) = stack
390 return then if if_ else else_, stack
394 @SimpleFunctionWrapper
397 Use a Boolean value to select one of two items from a sequence.
401 ------------------------
406 -----------------------
409 The sequence can contain more than two items but not fewer.
410 Currently Python semantics are used to evaluate the "truthiness" of the
411 Boolean value (so empty string, zero, etc. are counted as false, etc.)
413 (flag, (choices, stack)) = stack
414 (else_, (then, _)) = choices
415 return then if flag else else_, stack
419 @SimpleFunctionWrapper
421 '''Given a list find the maximum.'''
423 return max(iter_stack(tos)), stack
427 @SimpleFunctionWrapper
429 '''Given a list find the minimum.'''
431 return min(iter_stack(tos)), stack
435 @SimpleFunctionWrapper
437 '''Given a quoted sequence of numbers return the sum.
439 sum == 0 swap [+] step
442 return sum(iter_stack(tos)), stack
446 @SimpleFunctionWrapper
449 Expects an item on the stack and a quote under it and removes that item
450 from the the quote. The item is only removed once.
454 ------------------------
458 (tos, (second, stack)) = S
459 l = list(iter_stack(second))
461 return list_to_stack(l), stack
465 @SimpleFunctionWrapper
467 '''Given a list remove duplicate items.'''
469 I = list(iter_stack(tos))
470 list_to_stack(sorted(set(I), key=I.index))
471 return list_to_stack(sorted(set(I), key=I.index)), stack
475 @SimpleFunctionWrapper
477 '''Given a list return it sorted.'''
479 return list_to_stack(sorted(iter_stack(tos))), stack
483 @SimpleFunctionWrapper
486 The cons operator expects a list on top of the stack and the potential
487 member below. The effect is to add the potential member into the
490 (tos, (second, stack)) = S
491 return (second, tos), stack
495 @SimpleFunctionWrapper
498 Inverse of cons, removes an item from the top of the list on the stack
499 and places it under the remaining list.
503 return tos, (item, stack)
507 @SimpleFunctionWrapper
509 '''Clear everything from the stack.
520 @SimpleFunctionWrapper
522 '''Duplicate the top item on the stack.'''
524 return tos, (tos, stack)
528 @SimpleFunctionWrapper
531 Copy the second item down on the stack to the top of the stack.
544 @SimpleFunctionWrapper
547 Copy the item at TOS under the second item of the stack.
555 (tos, (second, stack)) = S
556 return tos, (second, (tos, stack))
560 @SimpleFunctionWrapper
562 '''Swap the top two items on stack.'''
563 (tos, (second, stack)) = S
564 return second, (tos, stack)
568 @SimpleFunctionWrapper
571 old_stack, stack = stack
572 return stack, old_stack
576 @SimpleFunctionWrapper
579 The stack operator pushes onto the stack a list containing all the
580 elements of the stack.
586 @SimpleFunctionWrapper
589 The unstack operator expects a list on top of the stack and makes that
590 the stack discarding the rest of the stack.
596 @SimpleFunctionWrapper
598 '''Pop and discard the top item from the stack.'''
603 @SimpleFunctionWrapper
605 '''Pop and discard the second item from the stack.'''
606 (tos, (_, stack)) = stack
611 @SimpleFunctionWrapper
613 '''Pop and discard the third item from the stack.'''
614 (tos, (second, (_, stack))) = stack
615 return tos, (second, stack)
619 @SimpleFunctionWrapper
621 '''Pop and discard the first and second items from the stack.'''
626 @SimpleFunctionWrapper
628 '''Duplicate the second item on the stack.'''
629 (tos, (second, stack)) = S
630 return tos, (second, (second, stack))
634 @SimpleFunctionWrapper
636 '''Reverse the list on the top of the stack.
639 reverse == [] swap shunt
643 for term in iter_stack(tos):
649 @SimpleFunctionWrapper
651 '''Concatinate the two lists on the top of the stack.
654 [a b c] [d e f] concat
655 ----------------------------
659 (tos, (second, stack)) = S
660 return concat(second, tos), stack
664 @SimpleFunctionWrapper
666 '''Like concat but reverses the top list into the second.
669 shunt == [swons] step == reverse swap concat
671 [a b c] [d e f] shunt
672 ---------------------------
676 (tos, (second, stack)) = stack
679 second = term, second
684 @SimpleFunctionWrapper
687 Replace the two lists on the top of the stack with a list of the pairs
688 from each list. The smallest list sets the length of the result list.
690 (tos, (second, stack)) = S
693 for a, b in zip(iter_stack(tos), iter_stack(second))
695 return list_to_stack(accumulator), stack
699 @SimpleFunctionWrapper
703 return tos + 1, stack
707 @SimpleFunctionWrapper
711 return tos - 1, stack
715 @SimpleFunctionWrapper
726 a, (b, stack) = stack
732 return int(math.floor(n))
734 floor.__doc__ = math.floor.__doc__
738 @SimpleFunctionWrapper
741 divmod(x, y) -> (quotient, remainder)
743 Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
752 Return the square root of the number a.
753 Negative numbers return complex roots.
758 assert a < 0, repr(a)
759 r = math.sqrt(-a) * 1j
764 @SimpleFunctionWrapper
774 (a, (b, (c, stack))) = S
775 return b, (c, (a, stack))
779 @SimpleFunctionWrapper
789 (a, (b, (c, stack))) = S
790 return c, (a, (b, stack))
795 # if isinstance(text, str):
796 # return run(text, stack)
801 @SimpleFunctionWrapper
803 '''The identity function.'''
808 @SimpleFunctionWrapper
810 '''True if the form on TOS is void otherwise False.'''
812 return _void(form), stack
816 return any(not _void(i) for i in iter_stack(form))
827 def words(stack, expression, dictionary):
828 '''Print all the words in alphabetical order.'''
829 print(' '.join(sorted(dictionary)))
830 return stack, expression, dictionary
835 def sharing(stack, expression, dictionary):
836 '''Print redistribution information.'''
837 print("You may convey verbatim copies of the Program's source code as"
838 ' you receive it, in any medium, provided that you conspicuously'
839 ' and appropriately publish on each copy an appropriate copyright'
840 ' notice; keep intact all notices stating that this License and'
841 ' any non-permissive terms added in accord with section 7 apply'
842 ' to the code; keep intact all notices of the absence of any'
843 ' warranty; and give all recipients a copy of this License along'
845 ' You should have received a copy of the GNU General Public License'
846 ' along with Thun. If not see <http://www.gnu.org/licenses/>.')
847 return stack, expression, dictionary
852 def warranty(stack, expression, dictionary):
853 '''Print warranty information.'''
854 print('THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY'
855 ' APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE'
856 ' COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM'
857 ' "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR'
858 ' IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES'
859 ' OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE'
860 ' ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS'
861 ' WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE'
862 ' COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.')
863 return stack, expression, dictionary
866 # def simple_manual(stack):
868 # Print words and help for each word.
870 # for name, f in sorted(FUNCTIONS.items()):
872 # boxline = '+%s+' % ('-' * (len(name) + 2))
875 # '| %s |' % (name,),
877 # d if d else ' ...',
887 def help_(S, expression, dictionary):
888 '''Accepts a quoted symbol on the top of the stack and prints its docs.'''
889 ((symbol, _), stack) = S
890 word = dictionary[symbol]
892 return stack, expression, dictionary
900 # Several combinators depend on other words in their definitions,
901 # we use symbols to prevent hard-coding these, so in theory, you
902 # could change the word in the dictionary to use different semantics.
903 S_choice = Symbol('choice')
904 S_first = Symbol('first')
905 S_getitem = Symbol('getitem')
906 S_genrec = Symbol('genrec')
907 S_loop = Symbol('loop')
909 S_ifte = Symbol('ifte')
910 S_infra = Symbol('infra')
911 S_step = Symbol('step')
912 S_times = Symbol('times')
913 S_swaack = Symbol('swaack')
914 S_truthy = Symbol('truthy')
919 def i(stack, expression, dictionary):
921 The i combinator expects a quoted program on the stack and unpacks it
922 onto the pending expression for evaluation.
931 return stack, concat(quote, expression), dictionary
936 def x(stack, expression, dictionary):
942 ... [Q] x = ... [Q] dup i
943 ... [Q] x = ... [Q] [Q] i
944 ... [Q] x = ... [Q] Q
948 return stack, concat(quote, expression), dictionary
953 def b(stack, expression, dictionary):
959 ... [P] [Q] b == ... [P] i [Q] i
960 ... [P] [Q] b == ... P Q
963 q, (p, (stack)) = stack
964 return stack, concat(p, concat(q, expression)), dictionary
969 def dupdip(stack, expression, dictionary):
973 [F] dupdip == dup [F] dip
983 return stack, concat(F, (a, expression)), dictionary
988 def infra(stack, expression, dictionary):
990 Accept a quoted program and a list on the stack and run the program
991 with the list as its stack.
994 ... [a b c] [Q] . infra
995 -----------------------------
996 c b a . Q [...] swaack
999 (quote, (aggregate, stack)) = stack
1000 return aggregate, concat(quote, (stack, (S_swaack, expression))), dictionary
1005 def genrec(stack, expression, dictionary):
1007 General Recursion Combinator.
1010 [if] [then] [rec1] [rec2] genrec
1011 ---------------------------------------------------------------------
1012 [if] [then] [rec1 [[if] [then] [rec1] [rec2] genrec] rec2] ifte
1014 From "Recursion Theory and Joy" (j05cmp.html) by Manfred von Thun:
1015 "The genrec combinator takes four program parameters in addition to
1016 whatever data parameters it needs. Fourth from the top is an if-part,
1017 followed by a then-part. If the if-part yields true, then the then-part
1018 is executed and the combinator terminates. The other two parameters are
1019 the rec1-part and the rec2-part. If the if-part yields false, the
1020 rec1-part is executed. Following that the four program parameters and
1021 the combinator are again pushed onto the stack bundled up in a quoted
1022 form. Then the rec2-part is executed, where it will find the bundled
1023 form. Typically it will then execute the bundled form, either with i or
1024 with app2, or some other combinator."
1026 The way to design one of these is to fix your base case [then] and the
1027 test [if], and then treat rec1 and rec2 as an else-part "sandwiching"
1028 a quotation of the whole function.
1030 For example, given a (general recursive) function 'F':
1033 F == [I] [T] [R1] [R2] genrec
1035 If the [I] if-part fails you must derive R1 and R2 from:
1040 Just set the stack arguments in front, and figure out what R1 and R2
1041 have to do to apply the quoted [F] in the proper way. In effect, the
1042 genrec combinator turns into an ifte combinator with a quoted copy of
1043 the original definition in the else-part:
1046 F == [I] [T] [R1] [R2] genrec
1047 == [I] [T] [R1 [F] R2] ifte
1049 Primitive recursive functions are those where R2 == i.
1052 P == [I] [T] [R] primrec
1053 == [I] [T] [R [P] i] ifte
1054 == [I] [T] [R P] ifte
1057 (rec2, (rec1, stack)) = stack
1058 (then, (if_, _)) = stack
1059 F = (if_, (then, (rec1, (rec2, (S_genrec, ())))))
1060 else_ = concat(rec1, (F, rec2))
1061 return (else_, stack), (S_ifte, expression), dictionary
1066 def map_(S, expression, dictionary):
1068 Run the quoted program on TOS on the items in the list under it, push a
1069 new list with the results (in place of the program and original list.
1071 # (quote, (aggregate, stack)) = S
1072 # results = list_to_stack([
1073 # joy((term, stack), quote, dictionary)[0][0]
1074 # for term in iter_stack(aggregate)
1076 # return (results, stack), expression, dictionary
1077 (quote, (aggregate, stack)) = S
1079 return (aggregate, stack), expression, dictionary
1081 for term in iter_stack(aggregate):
1083 batch = (s, (quote, (S_infra, (S_first, batch))))
1084 stack = (batch, ((), stack))
1085 return stack, (S_infra, expression), dictionary
1088 #def cleave(S, expression, dictionary):
1090 # The cleave combinator expects two quotations, and below that an item X.
1091 # It first executes [P], with X on top, and saves the top result element.
1092 # Then it executes [Q], again with X, and saves the top result.
1093 # Finally it restores the stack to what it was below X and pushes the two
1094 # results P(X) and Q(X).
1096 # (Q, (P, (x, stack))) = S
1097 # p = joy((x, stack), P, dictionary)[0][0]
1098 # q = joy((x, stack), Q, dictionary)[0][0]
1099 # return (q, (p, stack)), expression, dictionary
1104 def branch(stack, expression, dictionary):
1106 Use a Boolean value to select one of two quoted programs to run.
1110 branch == roll< choice i
1114 False [F] [T] branch
1115 --------------------------
1119 -------------------------
1123 (then, (else_, (flag, stack))) = stack
1124 return stack, concat(then if flag else else_, expression), dictionary
1129 def ifte(stack, expression, dictionary):
1131 If-Then-Else Combinator
1134 ... [if] [then] [else] ifte
1135 ---------------------------------------------------
1136 ... [[else] [then]] [...] [if] infra select i
1141 ... [if] [then] [else] ifte
1142 -------------------------------------------------------
1143 ... [else] [then] [...] [if] infra first choice i
1146 Has the effect of grabbing a copy of the stack on which to run the
1147 if-part using infra.
1149 (else_, (then, (if_, stack))) = stack
1150 expression = (S_infra, (S_first, (S_choice, (S_i, expression))))
1151 stack = (if_, (stack, (then, (else_, stack))))
1152 return stack, expression, dictionary
1157 def cond(stack, expression, dictionary):
1159 This combinator works like a case statement. It expects a single quote
1160 on the stack that must contain zero or more condition quotes and a
1161 default quote. Each condition clause should contain a quoted predicate
1162 followed by the function expression to run if that predicate returns
1163 true. If no predicates return true the default function runs.
1165 It works by rewriting into a chain of nested `ifte` expressions, e.g.::
1167 [[[B0] T0] [[B1] T1] [D]] cond
1168 -----------------------------------------
1169 [B0] [T0] [[B1] [T1] [D] ifte] ifte
1172 conditions, stack = stack
1174 expression = _cond(conditions, expression)
1176 # Attempt to preload the args to first ifte.
1177 (P, (T, (E, expression))) = expression
1179 # If, for any reason, the argument to cond should happen to contain
1180 # only the default clause then this optimization will fail.
1183 stack = (E, (T, (P, stack)))
1184 return stack, expression, dictionary
1187 def _cond(conditions, expression):
1188 (clause, rest) = conditions
1189 if not rest: # clause is [D]
1192 return (P, (T, (_cond(rest, ()), (S_ifte, expression))))
1197 def dip(stack, expression, dictionary):
1199 The dip combinator expects a quoted program on the stack and below it
1200 some item, it hoists the item into the expression and runs the program
1201 on the rest of the stack.
1209 (quote, (x, stack)) = stack
1210 expression = (x, expression)
1211 return stack, concat(quote, expression), dictionary
1216 def dipd(S, expression, dictionary):
1218 Like dip but expects two items.
1222 ---------------------
1226 (quote, (x, (y, stack))) = S
1227 expression = (y, (x, expression))
1228 return stack, concat(quote, expression), dictionary
1233 def dipdd(S, expression, dictionary):
1235 Like dip but expects three items.
1239 -----------------------
1243 (quote, (x, (y, (z, stack)))) = S
1244 expression = (z, (y, (x, expression)))
1245 return stack, concat(quote, expression), dictionary
1250 def app1(S, expression, dictionary):
1252 Given a quoted program on TOS and anything as the second stack item run
1253 the program and replace the two args with the first result of the
1258 -----------------------------------
1259 ... [x ...] [Q] . infra first
1261 (quote, (x, stack)) = S
1262 stack = (quote, ((x, stack), stack))
1263 expression = (S_infra, (S_first, expression))
1264 return stack, expression, dictionary
1269 def app2(S, expression, dictionary):
1270 '''Like app1 with two items.
1274 -----------------------------------
1275 ... [y ...] [Q] . infra first
1276 [x ...] [Q] infra first
1279 (quote, (x, (y, stack))) = S
1280 expression = (S_infra, (S_first,
1281 ((x, stack), (quote, (S_infra, (S_first,
1283 stack = (quote, ((y, stack), stack))
1284 return stack, expression, dictionary
1289 def app3(S, expression, dictionary):
1290 '''Like app1 with three items.
1293 ... z y x [Q] . app3
1294 -----------------------------------
1295 ... [z ...] [Q] . infra first
1296 [y ...] [Q] infra first
1297 [x ...] [Q] infra first
1300 (quote, (x, (y, (z, stack)))) = S
1301 expression = (S_infra, (S_first,
1302 ((y, stack), (quote, (S_infra, (S_first,
1303 ((x, stack), (quote, (S_infra, (S_first,
1304 expression))))))))))
1305 stack = (quote, ((z, stack), stack))
1306 return stack, expression, dictionary
1311 def step(S, expression, dictionary):
1313 Run a quoted program on each item in a sequence.
1317 -----------------------
1322 ------------------------
1326 ... [a b c] [Q] . step
1327 ----------------------------------------
1328 ... a . Q [b c] [Q] step
1330 The step combinator executes the quotation on each member of the list
1331 on top of the stack.
1333 (quote, (aggregate, stack)) = S
1335 return stack, expression, dictionary
1336 head, tail = aggregate
1337 stack = quote, (head, stack)
1339 expression = tail, (quote, (S_step, expression))
1340 expression = S_i, expression
1341 return stack, expression, dictionary
1346 def times(stack, expression, dictionary):
1348 times == [-- dip] cons [swap] infra [0 >] swap while pop
1352 --------------------- w/ n <= 0
1357 ---------------------------------
1362 --------------------------------- w/ n > 1
1363 ... . Q (n - 1) [Q] times
1366 # times == [-- dip] cons [swap] infra [0 >] swap while pop
1367 (quote, (n, stack)) = stack
1369 return stack, expression, dictionary
1372 expression = n, (quote, (S_times, expression))
1373 expression = concat(quote, expression)
1374 return stack, expression, dictionary
1377 # The current definition above works like this:
1380 # --------------------------------------
1381 # [P] nullary [Q [P] nullary] loop
1383 # while == [pop i not] [popop] [dudipd] primrec
1385 #def while_(S, expression, dictionary):
1386 # '''[if] [body] while'''
1387 # (body, (if_, stack)) = S
1388 # while joy(stack, if_, dictionary)[0][0]:
1389 # stack = joy(stack, body, dictionary)[0]
1390 # return stack, expression, dictionary
1395 def loop(stack, expression, dictionary):
1397 Basic loop combinator.
1401 -----------------------
1405 ------------------------
1409 quote, (flag, stack) = stack
1411 expression = concat(quote, (quote, (S_loop, expression)))
1412 return stack, expression, dictionary
1417 def cmp_(stack, expression, dictionary):
1419 cmp takes two values and three quoted programs on the stack and runs
1420 one of the three depending on the results of comparing the two values:
1424 ------------------------- a > b
1428 ------------------------- a = b
1432 ------------------------- a < b
1435 L, (E, (G, (b, (a, stack)))) = stack
1436 expression = concat(G if a > b else L if a < b else E, expression)
1437 return stack, expression, dictionary
1440 #def nullary(S, expression, dictionary):
1442 # Run the program on TOS and return its first result without consuming
1443 # any of the stack (except the program on TOS.)
1445 # (quote, stack) = S
1446 # result = joy(stack, quote, dictionary)
1447 # return (result[0][0], stack), expression, dictionary
1450 #def unary(S, expression, dictionary):
1451 # (quote, stack) = S
1452 # _, return_stack = stack
1453 # result = joy(stack, quote, dictionary)[0]
1454 # return (result[0], return_stack), expression, dictionary
1457 #def binary(S, expression, dictionary):
1458 # (quote, stack) = S
1459 # _, (_, return_stack) = stack
1460 # result = joy(stack, quote, dictionary)[0]
1461 # return (result[0], return_stack), expression, dictionary
1464 #def ternary(S, expression, dictionary):
1465 # (quote, stack) = S
1466 # _, (_, (_, return_stack)) = stack
1467 # result = joy(stack, quote, dictionary)[0]
1468 # return (result[0], return_stack), expression, dictionary
1471 # FunctionWrapper(binary),
1472 # FunctionWrapper(cleave),
1473 # FunctionWrapper(nullary),
1474 # FunctionWrapper(ternary),
1475 # FunctionWrapper(unary),
1476 # FunctionWrapper(while_),
1480 BinaryBuiltinWrapper(operator.add),
1481 BinaryBuiltinWrapper(operator.and_),
1482 BinaryBuiltinWrapper(operator.div),
1483 BinaryBuiltinWrapper(operator.eq),
1484 BinaryBuiltinWrapper(operator.floordiv),
1485 BinaryBuiltinWrapper(operator.ge),
1486 BinaryBuiltinWrapper(operator.gt),
1487 BinaryBuiltinWrapper(operator.le),
1488 BinaryBuiltinWrapper(operator.lshift),
1489 BinaryBuiltinWrapper(operator.lt),
1490 BinaryBuiltinWrapper(operator.mod),
1491 BinaryBuiltinWrapper(operator.mul),
1492 BinaryBuiltinWrapper(operator.ne),
1493 BinaryBuiltinWrapper(operator.or_),
1494 BinaryBuiltinWrapper(operator.pow),
1495 BinaryBuiltinWrapper(operator.rshift),
1496 BinaryBuiltinWrapper(operator.sub),
1497 BinaryBuiltinWrapper(operator.truediv),
1498 BinaryBuiltinWrapper(operator.xor),
1500 UnaryBuiltinWrapper(abs),
1501 UnaryBuiltinWrapper(bool),
1502 UnaryBuiltinWrapper(floor),
1503 UnaryBuiltinWrapper(operator.neg),
1504 UnaryBuiltinWrapper(operator.not_),
1505 UnaryBuiltinWrapper(sqrt),
1508 del F # Otherwise Sphinx autodoc will pick it up.
1511 add_aliases(_dictionary, ALIASES)
1514 DefinitionWrapper.add_definitions(definitions, _dictionary)