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
28 from inspect import getmembers, isfunction
31 from .parser import text_to_expression, Symbol
32 from .utils.stack import list_to_stack, iter_stack, pick, concat
33 from .utils.brutal_hackery import rename_code_object
35 from .utils import generated_library as genlib
41 def inscribe(function):
42 '''A decorator to inscribe functions into the default dictionary.'''
43 _dictionary[function.name] = function
48 '''Return a dictionary of Joy functions for use with joy().'''
49 return _dictionary.copy()
58 ('mod', ['%', 'rem', 'remainder', 'modulus']),
61 ('getitem', ['pick', 'at']),
72 ('rolldown', ['roll<']),
73 ('rollup', ['roll>']),
79 def add_aliases(D, A):
81 Given a dict and a iterable of (name, [alias, ...]) pairs, create
82 additional entries in the dict mapping each alias to the named function
83 if it's in the dict. Aliases for functions not in the dict are ignored.
85 for name, aliases in A:
96 product == 1 swap [*] step
97 flatten == [] swap [concat] step
100 enstacken == stack [clear] dip
101 disenstacken == ? [uncons ?] loop pop
103 dinfrirst == dip infra first
104 nullary == [stack] dinfrirst
105 unary == nullary popd
106 binary == nullary [popop] dip
107 ternary == unary [popop] dip
111 size == 0 swap [pop ++] step
113 cleave == fork [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
129 ifte == [nullary not] dipd branch
132 # ifte == [nullary] dipd swap branch
133 # genrec == [[genrec] cons cons cons cons] nullary swons concat ifte
135 # Another definition for while. FWIW
136 # while == over [[i] dip nullary] ccons [nullary] dip loop
140 ##second == rest first
141 ##third == rest rest first
143 ##swoncat == swap concat
146 ##z-down == [] swap uncons swap
147 ##z-up == swons swap shunt
148 ##z-right == [swons] cons dip uncons swap
149 ##z-left == swons [uncons swap] dip swap
152 ##divisor == popop 2 *
154 ##radical == swap dup * rollup * 4 * - sqrt
157 ##q0 == [[divisor] [minusb] [radical]] pam
158 ##q1 == [[root1] [root2]] pam
159 ##quadratic == [q0] ternary i [q1] ternary
163 ##PE1.1 == + dup [+] dip
164 ##PE1.2 == dup [3 & PE1.1] dip 2 >>
165 ##PE1.3 == 14811 swap [PE1.2] times pop
166 ##PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop
168 #PE1.2 == [PE1.1] step
169 #PE1 == 0 0 66 [[3 2 1 3 1 2 3] PE1.2] times [3 2 1 3] PE1.2 pop
173 def FunctionWrapper(f):
174 '''Set name attribute.'''
176 raise ValueError('Function %s must have doc string.' % f.__name__)
177 f.name = f.__name__.rstrip('_') # Don't shadow builtins.
181 def SimpleFunctionWrapper(f):
183 Wrap functions that take and return just a stack.
187 @rename_code_object(f.__name__)
188 def inner(stack, expression, dictionary):
189 return f(stack), expression, dictionary
193 def BinaryBuiltinWrapper(f):
195 Wrap functions that take two arguments and return a single result.
199 @rename_code_object(f.__name__)
200 def inner(stack, expression, dictionary):
201 (a, (b, stack)) = stack
203 return (result, stack), expression, dictionary
207 def UnaryBuiltinWrapper(f):
209 Wrap functions that take one argument and return a single result.
213 @rename_code_object(f.__name__)
214 def inner(stack, expression, dictionary):
217 return (result, stack), expression, dictionary
221 class DefinitionWrapper(object):
223 Provide implementation of defined functions, and some helper methods.
226 def __init__(self, name, body_text, doc=None):
227 self.name = self.__name__ = name
228 self.body = text_to_expression(body_text)
229 self._body = tuple(iter_stack(self.body))
230 self.__doc__ = doc or body_text
231 self._compiled = None
233 def __call__(self, stack, expression, dictionary):
235 return self._compiled(stack, expression, dictionary)
236 expression = list_to_stack(self._body, expression)
237 return stack, expression, dictionary
240 def parse_definition(class_, defi):
242 Given some text describing a Joy function definition parse it and
243 return a DefinitionWrapper.
245 name, proper, body_text = (n.strip() for n in defi.partition('=='))
247 raise ValueError('Definition %r failed' % (defi,))
248 return class_(name, body_text)
251 def add_definitions(class_, defs, dictionary):
253 Scan multi-line string defs for definitions and add them to the
256 for definition in _text_to_defs(defs):
257 class_.add_def(definition, dictionary)
260 def add_def(class_, definition, dictionary):
262 Add the definition to the dictionary.
264 F = class_.parse_definition(definition)
265 dictionary[F.name] = F
268 def _text_to_defs(text):
269 return (line.strip() for line in text.splitlines() if '==' in line)
277 # Load the auto-generated primitives into the dictionary.
278 for name, primitive in getmembers(genlib, isfunction):
279 inscribe(SimpleFunctionWrapper(primitive))
284 def inscribe_(stack, expression, dictionary):
286 Create a new Joy function definition in the Joy dictionary. A
287 definition is given as a string with a name followed by a double
288 equal sign then one or more Joy functions, the body. for example:
292 If you want the definition to persist over restarts, enter it into
293 the definitions.txt resource.
295 definition, stack = stack
296 DefinitionWrapper.add_def(definition, dictionary)
297 return stack, expression, dictionary
301 @SimpleFunctionWrapper
303 '''Parse the string on the stack to a Joy expression.'''
305 expression = text_to_expression(text)
306 return expression, stack
310 @SimpleFunctionWrapper
315 getitem == drop first
317 Expects an integer and a quote on the stack and returns the item at the
318 nth position in the quote counting from 0.
322 -------------------------
326 n, (Q, stack) = stack
327 return pick(Q, n), stack
331 @SimpleFunctionWrapper
338 Expects an integer and a quote on the stack and returns the quote with
339 n items removed off the top.
343 ----------------------
347 n, (Q, stack) = stack
358 @SimpleFunctionWrapper
361 Expects an integer and a quote on the stack and returns the quote with
362 just the top n items in reverse order (because that's easier and you can
363 use reverse if needed.)
367 ----------------------
371 n, (Q, stack) = stack
384 @SimpleFunctionWrapper
387 Use a Boolean value to select one of two items.
391 ----------------------
396 ---------------------
399 Currently Python semantics are used to evaluate the "truthiness" of the
400 Boolean value (so empty string, zero, etc. are counted as false, etc.)
402 (if_, (then, (else_, stack))) = stack
403 return then if if_ else else_, stack
407 @SimpleFunctionWrapper
410 Use a Boolean value to select one of two items from a sequence.
414 ------------------------
419 -----------------------
422 The sequence can contain more than two items but not fewer.
423 Currently Python semantics are used to evaluate the "truthiness" of the
424 Boolean value (so empty string, zero, etc. are counted as false, etc.)
426 (flag, (choices, stack)) = stack
427 (else_, (then, _)) = choices
428 return then if flag else else_, stack
432 @SimpleFunctionWrapper
434 '''Given a list find the maximum.'''
436 return max(iter_stack(tos)), stack
440 @SimpleFunctionWrapper
442 '''Given a list find the minimum.'''
444 return min(iter_stack(tos)), stack
448 @SimpleFunctionWrapper
450 '''Given a quoted sequence of numbers return the sum.
452 sum == 0 swap [+] step
455 return sum(iter_stack(tos)), stack
459 @SimpleFunctionWrapper
462 Expects an item on the stack and a quote under it and removes that item
463 from the the quote. The item is only removed once.
467 ------------------------
471 (tos, (second, stack)) = S
472 l = list(iter_stack(second))
474 return list_to_stack(l), stack
478 @SimpleFunctionWrapper
480 '''Given a list remove duplicate items.'''
482 I = list(iter_stack(tos))
483 list_to_stack(sorted(set(I), key=I.index))
484 return list_to_stack(sorted(set(I), key=I.index)), stack
488 @SimpleFunctionWrapper
490 '''Given a list return it sorted.'''
492 return list_to_stack(sorted(iter_stack(tos))), stack
496 @SimpleFunctionWrapper
498 '''Clear everything from the stack.
501 clear == stack [pop stack] loop
511 @SimpleFunctionWrapper
514 The unstack operator expects a list on top of the stack and makes that
515 the stack discarding the rest of the stack.
521 @SimpleFunctionWrapper
523 '''Reverse the list on the top of the stack.
526 reverse == [] swap shunt
530 for term in iter_stack(tos):
536 @SimpleFunctionWrapper
538 '''Concatinate the two lists on the top of the stack.
541 [a b c] [d e f] concat
542 ----------------------------
546 (tos, (second, stack)) = S
547 return concat(second, tos), stack
551 @SimpleFunctionWrapper
553 '''Like concat but reverses the top list into the second.
556 shunt == [swons] step == reverse swap concat
558 [a b c] [d e f] shunt
559 ---------------------------
563 (tos, (second, stack)) = stack
566 second = term, second
571 @SimpleFunctionWrapper
574 Replace the two lists on the top of the stack with a list of the pairs
575 from each list. The smallest list sets the length of the result list.
577 (tos, (second, stack)) = S
580 for a, b in zip(iter_stack(tos), iter_stack(second))
582 return list_to_stack(accumulator), stack
586 @SimpleFunctionWrapper
590 return tos + 1, stack
594 @SimpleFunctionWrapper
598 return tos - 1, stack
602 @SimpleFunctionWrapper
613 a, (b, stack) = stack
619 return int(math.floor(n))
621 floor.__doc__ = math.floor.__doc__
625 @SimpleFunctionWrapper
628 divmod(x, y) -> (quotient, remainder)
630 Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
639 Return the square root of the number a.
640 Negative numbers return complex roots.
645 assert a < 0, repr(a)
646 r = math.sqrt(-a) * 1j
652 # if isinstance(text, str):
653 # return run(text, stack)
658 @SimpleFunctionWrapper
660 '''The identity function.'''
665 @SimpleFunctionWrapper
667 '''True if the form on TOS is void otherwise False.'''
669 return _void(form), stack
673 return any(not _void(i) for i in iter_stack(form))
684 def words(stack, expression, dictionary):
685 '''Print all the words in alphabetical order.'''
686 print(' '.join(sorted(dictionary)))
687 return stack, expression, dictionary
692 def sharing(stack, expression, dictionary):
693 '''Print redistribution information.'''
694 print("You may convey verbatim copies of the Program's source code as"
695 ' you receive it, in any medium, provided that you conspicuously'
696 ' and appropriately publish on each copy an appropriate copyright'
697 ' notice; keep intact all notices stating that this License and'
698 ' any non-permissive terms added in accord with section 7 apply'
699 ' to the code; keep intact all notices of the absence of any'
700 ' warranty; and give all recipients a copy of this License along'
702 ' You should have received a copy of the GNU General Public License'
703 ' along with Thun. If not see <http://www.gnu.org/licenses/>.')
704 return stack, expression, dictionary
709 def warranty(stack, expression, dictionary):
710 '''Print warranty information.'''
711 print('THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY'
712 ' APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE'
713 ' COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM'
714 ' "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR'
715 ' IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES'
716 ' OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE'
717 ' ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS'
718 ' WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE'
719 ' COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.')
720 return stack, expression, dictionary
723 # def simple_manual(stack):
725 # Print words and help for each word.
727 # for name, f in sorted(FUNCTIONS.items()):
729 # boxline = '+%s+' % ('-' * (len(name) + 2))
732 # '| %s |' % (name,),
734 # d if d else ' ...',
744 def help_(S, expression, dictionary):
745 '''Accepts a quoted symbol on the top of the stack and prints its docs.'''
746 ((symbol, _), stack) = S
747 word = dictionary[symbol]
749 return stack, expression, dictionary
757 # Several combinators depend on other words in their definitions,
758 # we use symbols to prevent hard-coding these, so in theory, you
759 # could change the word in the dictionary to use different semantics.
760 S_choice = Symbol('choice')
761 S_first = Symbol('first')
762 S_getitem = Symbol('getitem')
763 S_genrec = Symbol('genrec')
764 S_loop = Symbol('loop')
766 S_ifte = Symbol('ifte')
767 S_infra = Symbol('infra')
768 S_step = Symbol('step')
769 S_times = Symbol('times')
770 S_swaack = Symbol('swaack')
771 S_truthy = Symbol('truthy')
776 def i(stack, expression, dictionary):
778 The i combinator expects a quoted program on the stack and unpacks it
779 onto the pending expression for evaluation.
788 return stack, concat(quote, expression), dictionary
793 def x(stack, expression, dictionary):
799 ... [Q] x = ... [Q] dup i
800 ... [Q] x = ... [Q] [Q] i
801 ... [Q] x = ... [Q] Q
805 return stack, concat(quote, expression), dictionary
810 def b(stack, expression, dictionary):
816 ... [P] [Q] b == ... [P] i [Q] i
817 ... [P] [Q] b == ... P Q
820 q, (p, (stack)) = stack
821 return stack, concat(p, concat(q, expression)), dictionary
826 def dupdip(stack, expression, dictionary):
830 [F] dupdip == dup [F] dip
840 return stack, concat(F, (a, expression)), dictionary
845 def infra(stack, expression, dictionary):
847 Accept a quoted program and a list on the stack and run the program
848 with the list as its stack.
851 ... [a b c] [Q] . infra
852 -----------------------------
853 c b a . Q [...] swaack
856 (quote, (aggregate, stack)) = stack
857 return aggregate, concat(quote, (stack, (S_swaack, expression))), dictionary
862 def genrec(stack, expression, dictionary):
864 General Recursion Combinator.
867 [if] [then] [rec1] [rec2] genrec
868 ---------------------------------------------------------------------
869 [if] [then] [rec1 [[if] [then] [rec1] [rec2] genrec] rec2] ifte
871 From "Recursion Theory and Joy" (j05cmp.html) by Manfred von Thun:
872 "The genrec combinator takes four program parameters in addition to
873 whatever data parameters it needs. Fourth from the top is an if-part,
874 followed by a then-part. If the if-part yields true, then the then-part
875 is executed and the combinator terminates. The other two parameters are
876 the rec1-part and the rec2-part. If the if-part yields false, the
877 rec1-part is executed. Following that the four program parameters and
878 the combinator are again pushed onto the stack bundled up in a quoted
879 form. Then the rec2-part is executed, where it will find the bundled
880 form. Typically it will then execute the bundled form, either with i or
881 with app2, or some other combinator."
883 The way to design one of these is to fix your base case [then] and the
884 test [if], and then treat rec1 and rec2 as an else-part "sandwiching"
885 a quotation of the whole function.
887 For example, given a (general recursive) function 'F':
890 F == [I] [T] [R1] [R2] genrec
892 If the [I] if-part fails you must derive R1 and R2 from:
897 Just set the stack arguments in front, and figure out what R1 and R2
898 have to do to apply the quoted [F] in the proper way. In effect, the
899 genrec combinator turns into an ifte combinator with a quoted copy of
900 the original definition in the else-part:
903 F == [I] [T] [R1] [R2] genrec
904 == [I] [T] [R1 [F] R2] ifte
906 Primitive recursive functions are those where R2 == i.
909 P == [I] [T] [R] primrec
910 == [I] [T] [R [P] i] ifte
911 == [I] [T] [R P] ifte
914 (rec2, (rec1, stack)) = stack
915 (then, (if_, _)) = stack
916 F = (if_, (then, (rec1, (rec2, (S_genrec, ())))))
917 else_ = concat(rec1, (F, rec2))
918 return (else_, stack), (S_ifte, expression), dictionary
923 def map_(S, expression, dictionary):
925 Run the quoted program on TOS on the items in the list under it, push a
926 new list with the results (in place of the program and original list.
928 # (quote, (aggregate, stack)) = S
929 # results = list_to_stack([
930 # joy((term, stack), quote, dictionary)[0][0]
931 # for term in iter_stack(aggregate)
933 # return (results, stack), expression, dictionary
934 (quote, (aggregate, stack)) = S
936 return (aggregate, stack), expression, dictionary
938 for term in iter_stack(aggregate):
940 batch = (s, (quote, (S_infra, (S_first, batch))))
941 stack = (batch, ((), stack))
942 return stack, (S_infra, expression), dictionary
945 #def cleave(S, expression, dictionary):
947 # The cleave combinator expects two quotations, and below that an item X.
948 # It first executes [P], with X on top, and saves the top result element.
949 # Then it executes [Q], again with X, and saves the top result.
950 # Finally it restores the stack to what it was below X and pushes the two
951 # results P(X) and Q(X).
953 # (Q, (P, (x, stack))) = S
954 # p = joy((x, stack), P, dictionary)[0][0]
955 # q = joy((x, stack), Q, dictionary)[0][0]
956 # return (q, (p, stack)), expression, dictionary
961 def branch(stack, expression, dictionary):
963 Use a Boolean value to select one of two quoted programs to run.
967 branch == roll< choice i
972 --------------------------
976 -------------------------
980 (then, (else_, (flag, stack))) = stack
981 return stack, concat(then if flag else else_, expression), dictionary
986 ##def ifte(stack, expression, dictionary):
988 ## If-Then-Else Combinator
991 ## ... [if] [then] [else] ifte
992 ## ---------------------------------------------------
993 ## ... [[else] [then]] [...] [if] infra select i
998 ## ... [if] [then] [else] ifte
999 ## -------------------------------------------------------
1000 ## ... [else] [then] [...] [if] infra first choice i
1003 ## Has the effect of grabbing a copy of the stack on which to run the
1004 ## if-part using infra.
1006 ## (else_, (then, (if_, stack))) = stack
1007 ## expression = (S_infra, (S_first, (S_choice, (S_i, expression))))
1008 ## stack = (if_, (stack, (then, (else_, stack))))
1009 ## return stack, expression, dictionary
1014 def cond(stack, expression, dictionary):
1016 This combinator works like a case statement. It expects a single quote
1017 on the stack that must contain zero or more condition quotes and a
1018 default quote. Each condition clause should contain a quoted predicate
1019 followed by the function expression to run if that predicate returns
1020 true. If no predicates return true the default function runs.
1022 It works by rewriting into a chain of nested `ifte` expressions, e.g.::
1024 [[[B0] T0] [[B1] T1] [D]] cond
1025 -----------------------------------------
1026 [B0] [T0] [[B1] [T1] [D] ifte] ifte
1029 conditions, stack = stack
1031 expression = _cond(conditions, expression)
1033 # Attempt to preload the args to first ifte.
1034 (P, (T, (E, expression))) = expression
1036 # If, for any reason, the argument to cond should happen to contain
1037 # only the default clause then this optimization will fail.
1040 stack = (E, (T, (P, stack)))
1041 return stack, expression, dictionary
1044 def _cond(conditions, expression):
1045 (clause, rest) = conditions
1046 if not rest: # clause is [D]
1049 return (P, (T, (_cond(rest, ()), (S_ifte, expression))))
1054 def dip(stack, expression, dictionary):
1056 The dip combinator expects a quoted program on the stack and below it
1057 some item, it hoists the item into the expression and runs the program
1058 on the rest of the stack.
1066 (quote, (x, stack)) = stack
1067 expression = (x, expression)
1068 return stack, concat(quote, expression), dictionary
1073 def dipd(S, expression, dictionary):
1075 Like dip but expects two items.
1079 ---------------------
1083 (quote, (x, (y, stack))) = S
1084 expression = (y, (x, expression))
1085 return stack, concat(quote, expression), dictionary
1090 def dipdd(S, expression, dictionary):
1092 Like dip but expects three items.
1096 -----------------------
1100 (quote, (x, (y, (z, stack)))) = S
1101 expression = (z, (y, (x, expression)))
1102 return stack, concat(quote, expression), dictionary
1107 def app1(S, expression, dictionary):
1109 Given a quoted program on TOS and anything as the second stack item run
1110 the program and replace the two args with the first result of the
1115 -----------------------------------
1116 ... [x ...] [Q] . infra first
1118 (quote, (x, stack)) = S
1119 stack = (quote, ((x, stack), stack))
1120 expression = (S_infra, (S_first, expression))
1121 return stack, expression, dictionary
1126 def app2(S, expression, dictionary):
1127 '''Like app1 with two items.
1131 -----------------------------------
1132 ... [y ...] [Q] . infra first
1133 [x ...] [Q] infra first
1136 (quote, (x, (y, stack))) = S
1137 expression = (S_infra, (S_first,
1138 ((x, stack), (quote, (S_infra, (S_first,
1140 stack = (quote, ((y, stack), stack))
1141 return stack, expression, dictionary
1146 def app3(S, expression, dictionary):
1147 '''Like app1 with three items.
1150 ... z y x [Q] . app3
1151 -----------------------------------
1152 ... [z ...] [Q] . infra first
1153 [y ...] [Q] infra first
1154 [x ...] [Q] infra first
1157 (quote, (x, (y, (z, stack)))) = S
1158 expression = (S_infra, (S_first,
1159 ((y, stack), (quote, (S_infra, (S_first,
1160 ((x, stack), (quote, (S_infra, (S_first,
1161 expression))))))))))
1162 stack = (quote, ((z, stack), stack))
1163 return stack, expression, dictionary
1168 def step(S, expression, dictionary):
1170 Run a quoted program on each item in a sequence.
1174 -----------------------
1179 ------------------------
1183 ... [a b c] [Q] . step
1184 ----------------------------------------
1185 ... a . Q [b c] [Q] step
1187 The step combinator executes the quotation on each member of the list
1188 on top of the stack.
1190 (quote, (aggregate, stack)) = S
1192 return stack, expression, dictionary
1193 head, tail = aggregate
1194 stack = quote, (head, stack)
1196 expression = tail, (quote, (S_step, expression))
1197 expression = S_i, expression
1198 return stack, expression, dictionary
1203 def times(stack, expression, dictionary):
1205 times == [-- dip] cons [swap] infra [0 >] swap while pop
1209 --------------------- w/ n <= 0
1214 ---------------------------------
1219 --------------------------------- w/ n > 1
1220 ... . Q (n - 1) [Q] times
1223 # times == [-- dip] cons [swap] infra [0 >] swap while pop
1224 (quote, (n, stack)) = stack
1226 return stack, expression, dictionary
1229 expression = n, (quote, (S_times, expression))
1230 expression = concat(quote, expression)
1231 return stack, expression, dictionary
1234 # The current definition above works like this:
1237 # --------------------------------------
1238 # [P] nullary [Q [P] nullary] loop
1240 # while == [pop i not] [popop] [dudipd] primrec
1242 #def while_(S, expression, dictionary):
1243 # '''[if] [body] while'''
1244 # (body, (if_, stack)) = S
1245 # while joy(stack, if_, dictionary)[0][0]:
1246 # stack = joy(stack, body, dictionary)[0]
1247 # return stack, expression, dictionary
1252 def loop(stack, expression, dictionary):
1254 Basic loop combinator.
1258 -----------------------
1262 ------------------------
1266 quote, (flag, stack) = stack
1268 expression = concat(quote, (quote, (S_loop, expression)))
1269 return stack, expression, dictionary
1274 def cmp_(stack, expression, dictionary):
1276 cmp takes two values and three quoted programs on the stack and runs
1277 one of the three depending on the results of comparing the two values:
1281 ------------------------- a > b
1285 ------------------------- a = b
1289 ------------------------- a < b
1292 L, (E, (G, (b, (a, stack)))) = stack
1293 expression = concat(G if a > b else L if a < b else E, expression)
1294 return stack, expression, dictionary
1297 # FunctionWrapper(cleave),
1298 # FunctionWrapper(while_),
1302 BinaryBuiltinWrapper(operator.add),
1303 BinaryBuiltinWrapper(operator.and_),
1304 BinaryBuiltinWrapper(operator.div),
1305 BinaryBuiltinWrapper(operator.eq),
1306 BinaryBuiltinWrapper(operator.floordiv),
1307 BinaryBuiltinWrapper(operator.ge),
1308 BinaryBuiltinWrapper(operator.gt),
1309 BinaryBuiltinWrapper(operator.le),
1310 BinaryBuiltinWrapper(operator.lshift),
1311 BinaryBuiltinWrapper(operator.lt),
1312 BinaryBuiltinWrapper(operator.mod),
1313 BinaryBuiltinWrapper(operator.mul),
1314 BinaryBuiltinWrapper(operator.ne),
1315 BinaryBuiltinWrapper(operator.or_),
1316 BinaryBuiltinWrapper(operator.pow),
1317 BinaryBuiltinWrapper(operator.rshift),
1318 BinaryBuiltinWrapper(operator.sub),
1319 BinaryBuiltinWrapper(operator.truediv),
1320 BinaryBuiltinWrapper(operator.xor),
1322 UnaryBuiltinWrapper(abs),
1323 UnaryBuiltinWrapper(bool),
1324 UnaryBuiltinWrapper(floor),
1325 UnaryBuiltinWrapper(operator.neg),
1326 UnaryBuiltinWrapper(operator.not_),
1327 UnaryBuiltinWrapper(sqrt),
1330 del F # Otherwise Sphinx autodoc will pick it up.
1333 add_aliases(_dictionary, ALIASES)
1336 DefinitionWrapper.add_definitions(definitions, _dictionary)