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, pushback
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=ALIASES):
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
130 ##z-down == [] swap uncons swap
131 ##z-up == swons swap shunt
132 ##z-right == [swons] cons dip uncons swap
133 ##z-left == swons [uncons swap] dip swap
136 ##divisor == popop 2 *
138 ##radical == swap dup * rollup * 4 * - sqrt
141 ##q0 == [[divisor] [minusb] [radical]] pam
142 ##q1 == [[root1] [root2]] pam
143 ##quadratic == [q0] ternary i [q1] ternary
147 ##PE1.1 == + dup [+] dip
148 ##PE1.2 == dup [3 & PE1.1] dip 2 >>
149 ##PE1.3 == 14811 swap [PE1.2] times pop
150 ##PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop
152 #PE1.2 == [PE1.1] step
153 #PE1 == 0 0 66 [[3 2 1 3 1 2 3] PE1.2] times [3 2 1 3] PE1.2 pop
157 def FunctionWrapper(f):
158 '''Set name attribute.'''
160 raise ValueError('Function %s must have doc string.' % f.__name__)
161 f.name = f.__name__.rstrip('_') # Don't shadow builtins.
165 def SimpleFunctionWrapper(f):
167 Wrap functions that take and return just a stack.
171 @rename_code_object(f.__name__)
172 def inner(stack, expression, dictionary):
173 return f(stack), expression, dictionary
177 def BinaryBuiltinWrapper(f):
179 Wrap functions that take two arguments and return a single result.
183 @rename_code_object(f.__name__)
184 def inner(stack, expression, dictionary):
185 (a, (b, stack)) = stack
187 return (result, stack), expression, dictionary
191 def UnaryBuiltinWrapper(f):
193 Wrap functions that take one argument and return a single result.
197 @rename_code_object(f.__name__)
198 def inner(stack, expression, dictionary):
201 return (result, stack), expression, dictionary
205 class DefinitionWrapper(object):
207 Provide implementation of defined functions, and some helper methods.
210 def __init__(self, name, body_text, doc=None):
211 self.name = self.__name__ = name
212 self.body = text_to_expression(body_text)
213 self._body = tuple(iter_stack(self.body))
214 self.__doc__ = doc or body_text
216 def __call__(self, stack, expression, dictionary):
217 expression = list_to_stack(self._body, expression)
218 return stack, expression, dictionary
221 def parse_definition(class_, defi):
223 Given some text describing a Joy function definition parse it and
224 return a DefinitionWrapper.
226 name, proper, body_text = (n.strip() for n in defi.partition('=='))
228 raise ValueError('Definition %r failed' % (defi,))
229 return class_(name, body_text)
232 def add_definitions(class_, defs, dictionary):
233 for definition in _text_to_defs(defs):
234 class_.add_def(definition, dictionary)
237 def add_def(class_, definition, dictionary):
238 F = class_.parse_definition(definition)
239 dictionary[F.name] = F
242 def _text_to_defs(text):
243 return (line.strip() for line in text.splitlines() if '==' in line)
252 @SimpleFunctionWrapper
253 def parse((text, stack)):
254 '''Parse the string on the stack to a Joy expression.'''
255 expression = text_to_expression(text)
256 return expression, stack
260 @SimpleFunctionWrapper
261 def first(((head, tail), stack)):
262 '''first == uncons pop'''
267 @SimpleFunctionWrapper
268 def rest(((head, tail), stack)):
269 '''rest == uncons popd'''
274 @SimpleFunctionWrapper
277 getitem == drop first
279 Expects an integer and a quote on the stack and returns the item at the
280 nth position in the quote counting from 0.
283 -------------------------
287 n, (Q, stack) = stack
288 return pick(Q, n), stack
292 @SimpleFunctionWrapper
297 Expects an integer and a quote on the stack and returns the quote with
298 n items removed off the top.
301 ----------------------
305 n, (Q, stack) = stack
316 @SimpleFunctionWrapper
319 Expects an integer and a quote on the stack and returns the quote with
320 just the top n items in reverse order (because that's easier and you can
321 use reverse if needed.)
324 ----------------------
328 n, (Q, stack) = stack
341 @SimpleFunctionWrapper
344 Use a Boolean value to select one of two items.
347 ----------------------
352 ---------------------
355 Currently Python semantics are used to evaluate the "truthiness" of the
356 Boolean value (so empty string, zero, etc. are counted as false, etc.)
358 (if_, (then, (else_, stack))) = stack
359 return then if if_ else else_, stack
363 @SimpleFunctionWrapper
366 Use a Boolean value to select one of two items from a sequence.
369 ------------------------
374 -----------------------
377 The sequence can contain more than two items but not fewer.
378 Currently Python semantics are used to evaluate the "truthiness" of the
379 Boolean value (so empty string, zero, etc. are counted as false, etc.)
381 (flag, (choices, stack)) = stack
382 (else_, (then, _)) = choices
383 return then if flag else else_, stack
387 @SimpleFunctionWrapper
389 '''Given a list find the maximum.'''
391 return max(iter_stack(tos)), stack
395 @SimpleFunctionWrapper
397 '''Given a list find the minimum.'''
399 return min(iter_stack(tos)), stack
403 @SimpleFunctionWrapper
405 '''Given a quoted sequence of numbers return the sum.
407 sum == 0 swap [+] step
410 return sum(iter_stack(tos)), stack
414 @SimpleFunctionWrapper
417 Expects an item on the stack and a quote under it and removes that item
418 from the the quote. The item is only removed once.
421 ------------------------
425 (tos, (second, stack)) = S
426 l = list(iter_stack(second))
428 return list_to_stack(l), stack
432 @SimpleFunctionWrapper
434 '''Given a list remove duplicate items.'''
436 I = list(iter_stack(tos))
437 list_to_stack(sorted(set(I), key=I.index))
438 return list_to_stack(sorted(set(I), key=I.index)), stack
442 @SimpleFunctionWrapper
444 '''Given a list return it sorted.'''
446 return list_to_stack(sorted(iter_stack(tos))), stack
450 @SimpleFunctionWrapper
453 The cons operator expects a list on top of the stack and the potential
454 member below. The effect is to add the potential member into the
457 (tos, (second, stack)) = S
458 return (second, tos), stack
462 @SimpleFunctionWrapper
465 Inverse of cons, removes an item from the top of the list on the stack
466 and places it under the remaining list.
470 return tos, (item, stack)
474 @SimpleFunctionWrapper
476 '''Clear everything from the stack.
486 @SimpleFunctionWrapper
488 '''Duplicate the top item on the stack.'''
490 return tos, (tos, stack)
494 @SimpleFunctionWrapper
497 Copy the second item down on the stack to the top of the stack.
509 @SimpleFunctionWrapper
512 Copy the item at TOS under the second item of the stack.
519 (tos, (second, stack)) = S
520 return tos, (second, (tos, stack))
524 @SimpleFunctionWrapper
526 '''Swap the top two items on stack.'''
527 (tos, (second, stack)) = S
528 return second, (tos, stack)
532 @SimpleFunctionWrapper
535 old_stack, stack = stack
536 return stack, old_stack
540 @SimpleFunctionWrapper
543 The stack operator pushes onto the stack a list containing all the
544 elements of the stack.
550 @SimpleFunctionWrapper
553 The unstack operator expects a list on top of the stack and makes that
554 the stack discarding the rest of the stack.
560 @SimpleFunctionWrapper
562 '''Pop and discard the top item from the stack.'''
567 @SimpleFunctionWrapper
569 '''Pop and discard the second item from the stack.'''
570 (tos, (_, stack)) = stack
575 @SimpleFunctionWrapper
577 '''Pop and discard the third item from the stack.'''
578 (tos, (second, (_, stack))) = stack
579 return tos, (second, stack)
583 @SimpleFunctionWrapper
585 '''Pop and discard the first and second items from the stack.'''
590 @SimpleFunctionWrapper
592 '''Duplicate the second item on the stack.'''
593 (tos, (second, stack)) = S
594 return tos, (second, (second, stack))
598 @SimpleFunctionWrapper
600 '''Reverse the list on the top of the stack.
602 reverse == [] swap shunt
606 for term in iter_stack(tos):
612 @SimpleFunctionWrapper
614 '''Concatinate the two lists on the top of the stack.'''
615 (tos, (second, stack)) = S
616 for term in reversed(list(iter_stack(second))):
622 @SimpleFunctionWrapper
623 def shunt((tos, (second, stack))):
625 shunt == [swons] step
627 Like concat but reverses the top list into the second.
631 second = term, second
636 @SimpleFunctionWrapper
639 Replace the two lists on the top of the stack with a list of the pairs
640 from each list. The smallest list sets the length of the result list.
642 (tos, (second, stack)) = S
645 for a, b in zip(iter_stack(tos), iter_stack(second))
647 return list_to_stack(accumulator), stack
651 @SimpleFunctionWrapper
655 return tos + 1, stack
659 @SimpleFunctionWrapper
663 return tos - 1, stack
667 @SimpleFunctionWrapper
677 a, (b, stack) = stack
683 return int(math.floor(n))
685 floor.__doc__ = math.floor.__doc__
689 @SimpleFunctionWrapper
692 divmod(x, y) -> (quotient, remainder)
694 Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
703 Return the square root of the number a.
704 Negative numbers return complex roots.
709 assert a < 0, repr(a)
710 r = math.sqrt(-a) * 1j
715 @SimpleFunctionWrapper
718 (a, (b, (c, stack))) = S
719 return b, (c, (a, stack))
723 @SimpleFunctionWrapper
726 (a, (b, (c, stack))) = S
727 return c, (a, (b, stack))
732 # if isinstance(text, str):
733 # return run(text, stack)
738 @SimpleFunctionWrapper
740 '''The identity function.'''
745 @SimpleFunctionWrapper
747 '''True if the form on TOS is void otherwise False.'''
749 return _void(form), stack
753 return any(not _void(i) for i in iter_stack(form))
764 def words(stack, expression, dictionary):
765 '''Print all the words in alphabetical order.'''
766 print(' '.join(sorted(dictionary)))
767 return stack, expression, dictionary
772 def sharing(stack, expression, dictionary):
773 '''Print redistribution information.'''
774 print("You may convey verbatim copies of the Program's source code as"
775 ' you receive it, in any medium, provided that you conspicuously'
776 ' and appropriately publish on each copy an appropriate copyright'
777 ' notice; keep intact all notices stating that this License and'
778 ' any non-permissive terms added in accord with section 7 apply'
779 ' to the code; keep intact all notices of the absence of any'
780 ' warranty; and give all recipients a copy of this License along'
782 ' You should have received a copy of the GNU General Public License'
783 ' along with Thun. If not see <http://www.gnu.org/licenses/>.')
784 return stack, expression, dictionary
789 def warranty(stack, expression, dictionary):
790 '''Print warranty information.'''
791 print('THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY'
792 ' APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE'
793 ' COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM'
794 ' "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR'
795 ' IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES'
796 ' OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE'
797 ' ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS'
798 ' WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE'
799 ' COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.')
800 return stack, expression, dictionary
803 # def simple_manual(stack):
805 # Print words and help for each word.
807 # for name, f in sorted(FUNCTIONS.items()):
809 # boxline = '+%s+' % ('-' * (len(name) + 2))
812 # '| %s |' % (name,),
814 # d if d else ' ...',
824 def help_(S, expression, dictionary):
825 '''Accepts a quoted symbol on the top of the stack and prints its docs.'''
826 ((symbol, _), stack) = S
827 word = dictionary[symbol]
829 return stack, expression, dictionary
837 # Several combinators depend on other words in their definitions,
838 # we use symbols to prevent hard-coding these, so in theory, you
839 # could change the word in the dictionary to use different semantics.
840 S_choice = Symbol('choice')
841 S_first = Symbol('first')
842 S_getitem = Symbol('getitem')
843 S_genrec = Symbol('genrec')
844 S_loop = Symbol('loop')
846 S_ifte = Symbol('ifte')
847 S_infra = Symbol('infra')
848 S_step = Symbol('step')
849 S_times = Symbol('times')
850 S_swaack = Symbol('swaack')
851 S_truthy = Symbol('truthy')
856 def i(stack, expression, dictionary):
858 The i combinator expects a quoted program on the stack and unpacks it
859 onto the pending expression for evaluation.
867 return stack, pushback(quote, expression), dictionary
872 def x(stack, expression, dictionary):
876 ... [Q] x = ... [Q] dup i
877 ... [Q] x = ... [Q] [Q] i
878 ... [Q] x = ... [Q] Q
882 return stack, pushback(quote, expression), dictionary
887 def b(stack, expression, dictionary):
891 ... [P] [Q] b == ... [P] i [Q] i
892 ... [P] [Q] b == ... P Q
895 q, (p, (stack)) = stack
896 return stack, pushback(p, pushback(q, expression)), dictionary
901 def dupdip(stack, expression, dictionary):
903 [F] dupdip == dup [F] dip
913 return stack, pushback(F, (a, expression)), dictionary
918 def infra(stack, expression, dictionary):
920 Accept a quoted program and a list on the stack and run the program
921 with the list as its stack.
923 ... [a b c] [Q] . infra
924 -----------------------------
925 c b a . Q [...] swaack
928 (quote, (aggregate, stack)) = stack
929 return aggregate, pushback(quote, (stack, (S_swaack, expression))), dictionary
934 def genrec(stack, expression, dictionary):
936 General Recursion Combinator.
938 [if] [then] [rec1] [rec2] genrec
939 ---------------------------------------------------------------------
940 [if] [then] [rec1 [[if] [then] [rec1] [rec2] genrec] rec2] ifte
942 From "Recursion Theory and Joy" (j05cmp.html) by Manfred von Thun:
943 "The genrec combinator takes four program parameters in addition to
944 whatever data parameters it needs. Fourth from the top is an if-part,
945 followed by a then-part. If the if-part yields true, then the then-part
946 is executed and the combinator terminates. The other two parameters are
947 the rec1-part and the rec2-part. If the if-part yields false, the
948 rec1-part is executed. Following that the four program parameters and
949 the combinator are again pushed onto the stack bundled up in a quoted
950 form. Then the rec2-part is executed, where it will find the bundled
951 form. Typically it will then execute the bundled form, either with i or
952 with app2, or some other combinator."
954 The way to design one of these is to fix your base case [then] and the
955 test [if], and then treat rec1 and rec2 as an else-part "sandwiching"
956 a quotation of the whole function.
958 For example, given a (general recursive) function 'F':
960 F == [I] [T] [R1] [R2] genrec
962 If the [I] if-part fails you must derive R1 and R2 from:
966 Just set the stack arguments in front, and figure out what R1 and R2
967 have to do to apply the quoted [F] in the proper way. In effect, the
968 genrec combinator turns into an ifte combinator with a quoted copy of
969 the original definition in the else-part:
971 F == [I] [T] [R1] [R2] genrec
972 == [I] [T] [R1 [F] R2] ifte
974 (Primitive recursive functions are those where R2 == i.
976 P == [I] [T] [R] primrec
977 == [I] [T] [R [P] i] ifte
978 == [I] [T] [R P] ifte
981 (rec2, (rec1, stack)) = stack
982 (then, (if_, _)) = stack
983 F = (if_, (then, (rec1, (rec2, (S_genrec, ())))))
984 else_ = pushback(rec1, (F, rec2))
985 return (else_, stack), (S_ifte, expression), dictionary
990 def map_(S, expression, dictionary):
992 Run the quoted program on TOS on the items in the list under it, push a
993 new list with the results (in place of the program and original list.
995 # (quote, (aggregate, stack)) = S
996 # results = list_to_stack([
997 # joy((term, stack), quote, dictionary)[0][0]
998 # for term in iter_stack(aggregate)
1000 # return (results, stack), expression, dictionary
1001 (quote, (aggregate, stack)) = S
1003 return (aggregate, stack), expression, dictionary
1005 for term in iter_stack(aggregate):
1007 batch = (s, (quote, (S_infra, (S_first, batch))))
1008 stack = (batch, ((), stack))
1009 return stack, (S_infra, expression), dictionary
1012 #def cleave(S, expression, dictionary):
1014 # The cleave combinator expects two quotations, and below that an item X.
1015 # It first executes [P], with X on top, and saves the top result element.
1016 # Then it executes [Q], again with X, and saves the top result.
1017 # Finally it restores the stack to what it was below X and pushes the two
1018 # results P(X) and Q(X).
1020 # (Q, (P, (x, stack))) = S
1021 # p = joy((x, stack), P, dictionary)[0][0]
1022 # q = joy((x, stack), Q, dictionary)[0][0]
1023 # return (q, (p, stack)), expression, dictionary
1028 def branch(stack, expression, dictionary):
1030 Use a Boolean value to select one of two quoted programs to run.
1032 branch == roll< choice i
1035 False [F] [T] branch
1036 --------------------------
1040 -------------------------
1044 (then, (else_, (flag, stack))) = stack
1045 return stack, pushback(then if flag else else_, expression), dictionary
1050 def ifte(stack, expression, dictionary):
1052 If-Then-Else Combinator
1054 ... [if] [then] [else] ifte
1055 ---------------------------------------------------
1056 ... [[else] [then]] [...] [if] infra select i
1061 ... [if] [then] [else] ifte
1062 -------------------------------------------------------
1063 ... [else] [then] [...] [if] infra first choice i
1066 Has the effect of grabbing a copy of the stack on which to run the
1067 if-part using infra.
1069 (else_, (then, (if_, stack))) = stack
1070 expression = (S_infra, (S_first, (S_choice, (S_i, expression))))
1071 stack = (if_, (stack, (then, (else_, stack))))
1072 return stack, expression, dictionary
1077 def dip(stack, expression, dictionary):
1079 The dip combinator expects a quoted program on the stack and below it
1080 some item, it hoists the item into the expression and runs the program
1081 on the rest of the stack.
1088 (quote, (x, stack)) = stack
1089 expression = (x, expression)
1090 return stack, pushback(quote, expression), dictionary
1095 def dipd(S, expression, dictionary):
1097 Like dip but expects two items.
1100 ---------------------
1104 (quote, (x, (y, stack))) = S
1105 expression = (y, (x, expression))
1106 return stack, pushback(quote, expression), dictionary
1111 def dipdd(S, expression, dictionary):
1113 Like dip but expects three items.
1116 -----------------------
1120 (quote, (x, (y, (z, stack)))) = S
1121 expression = (z, (y, (x, expression)))
1122 return stack, pushback(quote, expression), dictionary
1127 def app1(S, expression, dictionary):
1129 Given a quoted program on TOS and anything as the second stack item run
1130 the program and replace the two args with the first result of the
1134 -----------------------------------
1135 ... [x ...] [Q] . infra first
1137 (quote, (x, stack)) = S
1138 stack = (quote, ((x, stack), stack))
1139 expression = (S_infra, (S_first, expression))
1140 return stack, expression, dictionary
1145 def app2(S, expression, dictionary):
1146 '''Like app1 with two items.
1149 -----------------------------------
1150 ... [y ...] [Q] . infra first
1151 [x ...] [Q] infra first
1154 (quote, (x, (y, stack))) = S
1155 expression = (S_infra, (S_first,
1156 ((x, stack), (quote, (S_infra, (S_first,
1158 stack = (quote, ((y, stack), stack))
1159 return stack, expression, dictionary
1164 def app3(S, expression, dictionary):
1165 '''Like app1 with three items.
1167 ... z y x [Q] . app3
1168 -----------------------------------
1169 ... [z ...] [Q] . infra first
1170 [y ...] [Q] infra first
1171 [x ...] [Q] infra first
1174 (quote, (x, (y, (z, stack)))) = S
1175 expression = (S_infra, (S_first,
1176 ((y, stack), (quote, (S_infra, (S_first,
1177 ((x, stack), (quote, (S_infra, (S_first,
1178 expression))))))))))
1179 stack = (quote, ((z, stack), stack))
1180 return stack, expression, dictionary
1185 def step(S, expression, dictionary):
1187 Run a quoted program on each item in a sequence.
1190 -----------------------
1195 ------------------------
1199 ... [a b c] [Q] . step
1200 ----------------------------------------
1201 ... a . Q [b c] [Q] step
1203 The step combinator executes the quotation on each member of the list
1204 on top of the stack.
1206 (quote, (aggregate, stack)) = S
1208 return stack, expression, dictionary
1209 head, tail = aggregate
1210 stack = quote, (head, stack)
1212 expression = tail, (quote, (S_step, expression))
1213 expression = S_i, expression
1214 return stack, expression, dictionary
1219 def times(stack, expression, dictionary):
1221 times == [-- dip] cons [swap] infra [0 >] swap while pop
1224 --------------------- w/ n <= 0
1229 ---------------------------------
1234 --------------------------------- w/ n > 1
1235 ... . Q (n - 1) [Q] times
1238 # times == [-- dip] cons [swap] infra [0 >] swap while pop
1239 (quote, (n, stack)) = stack
1241 return stack, expression, dictionary
1244 expression = n, (quote, (S_times, expression))
1245 expression = pushback(quote, expression)
1246 return stack, expression, dictionary
1249 # The current definition above works like this:
1252 # --------------------------------------
1253 # [P] nullary [Q [P] nullary] loop
1255 # while == [pop i not] [popop] [dudipd] primrec
1257 #def while_(S, expression, dictionary):
1258 # '''[if] [body] while'''
1259 # (body, (if_, stack)) = S
1260 # while joy(stack, if_, dictionary)[0][0]:
1261 # stack = joy(stack, body, dictionary)[0]
1262 # return stack, expression, dictionary
1267 def loop(stack, expression, dictionary):
1269 Basic loop combinator.
1272 -----------------------
1276 ------------------------
1280 quote, (flag, stack) = stack
1282 expression = pushback(quote, (quote, (S_loop, expression)))
1283 return stack, expression, dictionary
1286 #def nullary(S, expression, dictionary):
1288 # Run the program on TOS and return its first result without consuming
1289 # any of the stack (except the program on TOS.)
1291 # (quote, stack) = S
1292 # result = joy(stack, quote, dictionary)
1293 # return (result[0][0], stack), expression, dictionary
1296 #def unary(S, expression, dictionary):
1297 # (quote, stack) = S
1298 # _, return_stack = stack
1299 # result = joy(stack, quote, dictionary)[0]
1300 # return (result[0], return_stack), expression, dictionary
1303 #def binary(S, expression, dictionary):
1304 # (quote, stack) = S
1305 # _, (_, return_stack) = stack
1306 # result = joy(stack, quote, dictionary)[0]
1307 # return (result[0], return_stack), expression, dictionary
1310 #def ternary(S, expression, dictionary):
1311 # (quote, stack) = S
1312 # _, (_, (_, return_stack)) = stack
1313 # result = joy(stack, quote, dictionary)[0]
1314 # return (result[0], return_stack), expression, dictionary
1317 # FunctionWrapper(binary),
1318 # FunctionWrapper(cleave),
1319 # FunctionWrapper(nullary),
1320 # FunctionWrapper(ternary),
1321 # FunctionWrapper(unary),
1322 # FunctionWrapper(while_),
1326 BinaryBuiltinWrapper(operator.add),
1327 BinaryBuiltinWrapper(operator.and_),
1328 BinaryBuiltinWrapper(operator.div),
1329 BinaryBuiltinWrapper(operator.eq),
1330 BinaryBuiltinWrapper(operator.floordiv),
1331 BinaryBuiltinWrapper(operator.ge),
1332 BinaryBuiltinWrapper(operator.gt),
1333 BinaryBuiltinWrapper(operator.le),
1334 BinaryBuiltinWrapper(operator.lshift),
1335 BinaryBuiltinWrapper(operator.lt),
1336 BinaryBuiltinWrapper(operator.mod),
1337 BinaryBuiltinWrapper(operator.mul),
1338 BinaryBuiltinWrapper(operator.ne),
1339 BinaryBuiltinWrapper(operator.or_),
1340 BinaryBuiltinWrapper(operator.pow),
1341 BinaryBuiltinWrapper(operator.rshift),
1342 BinaryBuiltinWrapper(operator.sub),
1343 BinaryBuiltinWrapper(operator.truediv),
1344 BinaryBuiltinWrapper(operator.xor),
1346 UnaryBuiltinWrapper(abs),
1347 UnaryBuiltinWrapper(bool),
1348 UnaryBuiltinWrapper(floor),
1349 UnaryBuiltinWrapper(operator.neg),
1350 UnaryBuiltinWrapper(operator.not_),
1351 UnaryBuiltinWrapper(sqrt),
1356 add_aliases(_dictionary)
1359 DefinitionWrapper.add_definitions(definitions, _dictionary)