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>']),
78 def add_aliases(D, A):
80 Given a dict and a iterable of (name, [alias, ...]) pairs, create
81 additional entries in the dict mapping each alias to the named function
82 if it's in the dict. Aliases for functions not in the dict are ignored.
84 for name, aliases in A:
95 product == 1 swap [*] step
96 flatten == [] swap [concat] step
99 enstacken == stack [clear] dip
100 disenstacken == ? [uncons ?] loop pop
102 dinfrirst == dip infra first
103 nullary == [stack] dinfrirst
104 unary == nullary popd
105 binary == nullary [popop] dip
106 ternary == unary [popop] dip
110 size == 0 swap [pop ++] step
111 cleave == [i] app2 [popd] dip
112 average == [sum 1.0 *] [size] cleave /
113 gcd == 1 [tuck modulus dup 0 >] loop pop
114 least_fraction == dup [gcd] infra [div] concat map
115 *fraction == [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons
116 *fraction0 == concat [[swap] dip * [*] dip] infra
117 down_to_zero == [0 >] [dup --] while
118 range_to_zero == unit [down_to_zero] infra
119 anamorphism == [pop []] swap [dip swons] genrec
120 range == [0 <=] [1 - dup] anamorphism
121 while == swap [nullary] cons dup dipd concat loop
123 primrec == [i] genrec
124 step_zero == 0 roll> step
125 codireco == cons dip rest cons
126 make_generator == [codireco] ccons
128 # ifte == [nullary not] dipd branch
129 # ifte == [nullary] dipd swap branch
133 ##second == rest first
134 ##third == rest rest first
136 ##swoncat == swap concat
139 ##z-down == [] swap uncons swap
140 ##z-up == swons swap shunt
141 ##z-right == [swons] cons dip uncons swap
142 ##z-left == swons [uncons swap] dip swap
145 ##divisor == popop 2 *
147 ##radical == swap dup * rollup * 4 * - sqrt
150 ##q0 == [[divisor] [minusb] [radical]] pam
151 ##q1 == [[root1] [root2]] pam
152 ##quadratic == [q0] ternary i [q1] ternary
156 ##PE1.1 == + dup [+] dip
157 ##PE1.2 == dup [3 & PE1.1] dip 2 >>
158 ##PE1.3 == 14811 swap [PE1.2] times pop
159 ##PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop
161 #PE1.2 == [PE1.1] step
162 #PE1 == 0 0 66 [[3 2 1 3 1 2 3] PE1.2] times [3 2 1 3] PE1.2 pop
166 def FunctionWrapper(f):
167 '''Set name attribute.'''
169 raise ValueError('Function %s must have doc string.' % f.__name__)
170 f.name = f.__name__.rstrip('_') # Don't shadow builtins.
174 def SimpleFunctionWrapper(f):
176 Wrap functions that take and return just a stack.
180 @rename_code_object(f.__name__)
181 def inner(stack, expression, dictionary):
182 return f(stack), expression, dictionary
186 def BinaryBuiltinWrapper(f):
188 Wrap functions that take two arguments and return a single result.
192 @rename_code_object(f.__name__)
193 def inner(stack, expression, dictionary):
194 (a, (b, stack)) = stack
196 return (result, stack), expression, dictionary
200 def UnaryBuiltinWrapper(f):
202 Wrap functions that take one argument and return a single result.
206 @rename_code_object(f.__name__)
207 def inner(stack, expression, dictionary):
210 return (result, stack), expression, dictionary
214 class DefinitionWrapper(object):
216 Provide implementation of defined functions, and some helper methods.
219 def __init__(self, name, body_text, doc=None):
220 self.name = self.__name__ = name
221 self.body = text_to_expression(body_text)
222 self._body = tuple(iter_stack(self.body))
223 self.__doc__ = doc or body_text
225 def __call__(self, stack, expression, dictionary):
226 expression = list_to_stack(self._body, expression)
227 return stack, expression, dictionary
230 def parse_definition(class_, defi):
232 Given some text describing a Joy function definition parse it and
233 return a DefinitionWrapper.
235 name, proper, body_text = (n.strip() for n in defi.partition('=='))
237 raise ValueError('Definition %r failed' % (defi,))
238 return class_(name, body_text)
241 def add_definitions(class_, defs, dictionary):
243 Scan multi-line string defs for definitions and add them to the
246 for definition in _text_to_defs(defs):
247 class_.add_def(definition, dictionary)
250 def add_def(class_, definition, dictionary):
252 Add the definition to the dictionary.
254 F = class_.parse_definition(definition)
255 dictionary[F.name] = F
258 def _text_to_defs(text):
259 return (line.strip() for line in text.splitlines() if '==' in line)
267 # Load the auto-generated primitives into the dictionary.
268 for name, primitive in getmembers(genlib, isfunction):
269 inscribe(SimpleFunctionWrapper(primitive))
273 @SimpleFunctionWrapper
275 '''Parse the string on the stack to a Joy expression.'''
277 expression = text_to_expression(text)
278 return expression, stack
282 ##@SimpleFunctionWrapper
287 ## first == uncons pop
290 ## ((head, tail), stack) = stack
291 ## return head, stack
295 ##@SimpleFunctionWrapper
300 ## rest == uncons popd
303 ## ((head, tail), stack) = stack
304 ## return tail, stack
308 @SimpleFunctionWrapper
313 getitem == drop first
315 Expects an integer and a quote on the stack and returns the item at the
316 nth position in the quote counting from 0.
320 -------------------------
324 n, (Q, stack) = stack
325 return pick(Q, n), stack
329 @SimpleFunctionWrapper
336 Expects an integer and a quote on the stack and returns the quote with
337 n items removed off the top.
341 ----------------------
345 n, (Q, stack) = stack
356 @SimpleFunctionWrapper
359 Expects an integer and a quote on the stack and returns the quote with
360 just the top n items in reverse order (because that's easier and you can
361 use reverse if needed.)
365 ----------------------
369 n, (Q, stack) = stack
382 @SimpleFunctionWrapper
385 Use a Boolean value to select one of two items.
389 ----------------------
394 ---------------------
397 Currently Python semantics are used to evaluate the "truthiness" of the
398 Boolean value (so empty string, zero, etc. are counted as false, etc.)
400 (if_, (then, (else_, stack))) = stack
401 return then if if_ else else_, stack
405 @SimpleFunctionWrapper
408 Use a Boolean value to select one of two items from a sequence.
412 ------------------------
417 -----------------------
420 The sequence can contain more than two items but not fewer.
421 Currently Python semantics are used to evaluate the "truthiness" of the
422 Boolean value (so empty string, zero, etc. are counted as false, etc.)
424 (flag, (choices, stack)) = stack
425 (else_, (then, _)) = choices
426 return then if flag else else_, stack
430 @SimpleFunctionWrapper
432 '''Given a list find the maximum.'''
434 return max(iter_stack(tos)), stack
438 @SimpleFunctionWrapper
440 '''Given a list find the minimum.'''
442 return min(iter_stack(tos)), stack
446 @SimpleFunctionWrapper
448 '''Given a quoted sequence of numbers return the sum.
450 sum == 0 swap [+] step
453 return sum(iter_stack(tos)), stack
457 @SimpleFunctionWrapper
460 Expects an item on the stack and a quote under it and removes that item
461 from the the quote. The item is only removed once.
465 ------------------------
469 (tos, (second, stack)) = S
470 l = list(iter_stack(second))
472 return list_to_stack(l), stack
476 @SimpleFunctionWrapper
478 '''Given a list remove duplicate items.'''
480 I = list(iter_stack(tos))
481 list_to_stack(sorted(set(I), key=I.index))
482 return list_to_stack(sorted(set(I), key=I.index)), stack
486 @SimpleFunctionWrapper
488 '''Given a list return it sorted.'''
490 return list_to_stack(sorted(iter_stack(tos))), stack
494 ##@SimpleFunctionWrapper
497 ## The cons operator expects a list on top of the stack and the potential
498 ## member below. The effect is to add the potential member into the
501 ## (tos, (second, stack)) = S
502 ## return (second, tos), stack
506 ##@SimpleFunctionWrapper
509 ## Inverse of cons, removes an item from the top of the list on the stack
510 ## and places it under the remaining list.
514 ## return tos, (item, stack)
518 @SimpleFunctionWrapper
520 '''Clear everything from the stack.
531 ##@SimpleFunctionWrapper
533 ## '''Duplicate the top item on the stack.'''
535 ## return tos, (tos, stack)
539 ##@SimpleFunctionWrapper
542 ## Copy the second item down on the stack to the top of the stack.
555 ##@SimpleFunctionWrapper
558 ## Copy the item at TOS under the second item of the stack.
566 ## (tos, (second, stack)) = S
567 ## return tos, (second, (tos, stack))
571 ##@SimpleFunctionWrapper
573 ## '''Swap the top two items on stack.'''
574 ## (tos, (second, stack)) = S
575 ## return second, (tos, stack)
579 ##@SimpleFunctionWrapper
582 ## old_stack, stack = stack
583 ## return stack, old_stack
587 ##@SimpleFunctionWrapper
590 ## The stack operator pushes onto the stack a list containing all the
591 ## elements of the stack.
593 ## return stack, stack
597 @SimpleFunctionWrapper
600 The unstack operator expects a list on top of the stack and makes that
601 the stack discarding the rest of the stack.
607 ##@SimpleFunctionWrapper
609 ## '''Pop and discard the top item from the stack.'''
614 ##@SimpleFunctionWrapper
616 ## '''Pop and discard the second item from the stack.'''
617 ## (tos, (_, stack)) = stack
622 ##@SimpleFunctionWrapper
624 ## '''Pop and discard the third item from the stack.'''
625 ## (tos, (second, (_, stack))) = stack
626 ## return tos, (second, stack)
630 ##@SimpleFunctionWrapper
632 ## '''Pop and discard the first and second items from the stack.'''
633 ## return stack[1][1]
637 ##@SimpleFunctionWrapper
639 ## '''Duplicate the second item on the stack.'''
640 ## (tos, (second, stack)) = S
641 ## return tos, (second, (second, stack))
645 @SimpleFunctionWrapper
647 '''Reverse the list on the top of the stack.
650 reverse == [] swap shunt
654 for term in iter_stack(tos):
660 @SimpleFunctionWrapper
662 '''Concatinate the two lists on the top of the stack.
665 [a b c] [d e f] concat
666 ----------------------------
670 (tos, (second, stack)) = S
671 return concat(second, tos), stack
675 @SimpleFunctionWrapper
677 '''Like concat but reverses the top list into the second.
680 shunt == [swons] step == reverse swap concat
682 [a b c] [d e f] shunt
683 ---------------------------
687 (tos, (second, stack)) = stack
690 second = term, second
695 @SimpleFunctionWrapper
698 Replace the two lists on the top of the stack with a list of the pairs
699 from each list. The smallest list sets the length of the result list.
701 (tos, (second, stack)) = S
704 for a, b in zip(iter_stack(tos), iter_stack(second))
706 return list_to_stack(accumulator), stack
710 @SimpleFunctionWrapper
714 return tos + 1, stack
718 @SimpleFunctionWrapper
722 return tos - 1, stack
726 @SimpleFunctionWrapper
737 a, (b, stack) = stack
743 return int(math.floor(n))
745 floor.__doc__ = math.floor.__doc__
749 @SimpleFunctionWrapper
752 divmod(x, y) -> (quotient, remainder)
754 Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
763 Return the square root of the number a.
764 Negative numbers return complex roots.
769 assert a < 0, repr(a)
770 r = math.sqrt(-a) * 1j
775 ##@SimpleFunctionWrapper
785 ## (a, (b, (c, stack))) = S
786 ## return b, (c, (a, stack))
790 ##@SimpleFunctionWrapper
800 ## (a, (b, (c, stack))) = S
801 ## return c, (a, (b, stack))
806 # if isinstance(text, str):
807 # return run(text, stack)
812 @SimpleFunctionWrapper
814 '''The identity function.'''
819 @SimpleFunctionWrapper
821 '''True if the form on TOS is void otherwise False.'''
823 return _void(form), stack
827 return any(not _void(i) for i in iter_stack(form))
838 def words(stack, expression, dictionary):
839 '''Print all the words in alphabetical order.'''
840 print(' '.join(sorted(dictionary)))
841 return stack, expression, dictionary
846 def sharing(stack, expression, dictionary):
847 '''Print redistribution information.'''
848 print("You may convey verbatim copies of the Program's source code as"
849 ' you receive it, in any medium, provided that you conspicuously'
850 ' and appropriately publish on each copy an appropriate copyright'
851 ' notice; keep intact all notices stating that this License and'
852 ' any non-permissive terms added in accord with section 7 apply'
853 ' to the code; keep intact all notices of the absence of any'
854 ' warranty; and give all recipients a copy of this License along'
856 ' You should have received a copy of the GNU General Public License'
857 ' along with Thun. If not see <http://www.gnu.org/licenses/>.')
858 return stack, expression, dictionary
863 def warranty(stack, expression, dictionary):
864 '''Print warranty information.'''
865 print('THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY'
866 ' APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE'
867 ' COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM'
868 ' "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR'
869 ' IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES'
870 ' OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE'
871 ' ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS'
872 ' WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE'
873 ' COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.')
874 return stack, expression, dictionary
877 # def simple_manual(stack):
879 # Print words and help for each word.
881 # for name, f in sorted(FUNCTIONS.items()):
883 # boxline = '+%s+' % ('-' * (len(name) + 2))
886 # '| %s |' % (name,),
888 # d if d else ' ...',
898 def help_(S, expression, dictionary):
899 '''Accepts a quoted symbol on the top of the stack and prints its docs.'''
900 ((symbol, _), stack) = S
901 word = dictionary[symbol]
903 return stack, expression, dictionary
911 # Several combinators depend on other words in their definitions,
912 # we use symbols to prevent hard-coding these, so in theory, you
913 # could change the word in the dictionary to use different semantics.
914 S_choice = Symbol('choice')
915 S_first = Symbol('first')
916 S_getitem = Symbol('getitem')
917 S_genrec = Symbol('genrec')
918 S_loop = Symbol('loop')
920 S_ifte = Symbol('ifte')
921 S_infra = Symbol('infra')
922 S_step = Symbol('step')
923 S_times = Symbol('times')
924 S_swaack = Symbol('swaack')
925 S_truthy = Symbol('truthy')
930 def i(stack, expression, dictionary):
932 The i combinator expects a quoted program on the stack and unpacks it
933 onto the pending expression for evaluation.
942 return stack, concat(quote, expression), dictionary
947 def x(stack, expression, dictionary):
953 ... [Q] x = ... [Q] dup i
954 ... [Q] x = ... [Q] [Q] i
955 ... [Q] x = ... [Q] Q
959 return stack, concat(quote, expression), dictionary
964 def b(stack, expression, dictionary):
970 ... [P] [Q] b == ... [P] i [Q] i
971 ... [P] [Q] b == ... P Q
974 q, (p, (stack)) = stack
975 return stack, concat(p, concat(q, expression)), dictionary
980 def dupdip(stack, expression, dictionary):
984 [F] dupdip == dup [F] dip
994 return stack, concat(F, (a, expression)), dictionary
999 def infra(stack, expression, dictionary):
1001 Accept a quoted program and a list on the stack and run the program
1002 with the list as its stack.
1005 ... [a b c] [Q] . infra
1006 -----------------------------
1007 c b a . Q [...] swaack
1010 (quote, (aggregate, stack)) = stack
1011 return aggregate, concat(quote, (stack, (S_swaack, expression))), dictionary
1016 def genrec(stack, expression, dictionary):
1018 General Recursion Combinator.
1021 [if] [then] [rec1] [rec2] genrec
1022 ---------------------------------------------------------------------
1023 [if] [then] [rec1 [[if] [then] [rec1] [rec2] genrec] rec2] ifte
1025 From "Recursion Theory and Joy" (j05cmp.html) by Manfred von Thun:
1026 "The genrec combinator takes four program parameters in addition to
1027 whatever data parameters it needs. Fourth from the top is an if-part,
1028 followed by a then-part. If the if-part yields true, then the then-part
1029 is executed and the combinator terminates. The other two parameters are
1030 the rec1-part and the rec2-part. If the if-part yields false, the
1031 rec1-part is executed. Following that the four program parameters and
1032 the combinator are again pushed onto the stack bundled up in a quoted
1033 form. Then the rec2-part is executed, where it will find the bundled
1034 form. Typically it will then execute the bundled form, either with i or
1035 with app2, or some other combinator."
1037 The way to design one of these is to fix your base case [then] and the
1038 test [if], and then treat rec1 and rec2 as an else-part "sandwiching"
1039 a quotation of the whole function.
1041 For example, given a (general recursive) function 'F':
1044 F == [I] [T] [R1] [R2] genrec
1046 If the [I] if-part fails you must derive R1 and R2 from:
1051 Just set the stack arguments in front, and figure out what R1 and R2
1052 have to do to apply the quoted [F] in the proper way. In effect, the
1053 genrec combinator turns into an ifte combinator with a quoted copy of
1054 the original definition in the else-part:
1057 F == [I] [T] [R1] [R2] genrec
1058 == [I] [T] [R1 [F] R2] ifte
1060 Primitive recursive functions are those where R2 == i.
1063 P == [I] [T] [R] primrec
1064 == [I] [T] [R [P] i] ifte
1065 == [I] [T] [R P] ifte
1068 (rec2, (rec1, stack)) = stack
1069 (then, (if_, _)) = stack
1070 F = (if_, (then, (rec1, (rec2, (S_genrec, ())))))
1071 else_ = concat(rec1, (F, rec2))
1072 return (else_, stack), (S_ifte, expression), dictionary
1077 def map_(S, expression, dictionary):
1079 Run the quoted program on TOS on the items in the list under it, push a
1080 new list with the results (in place of the program and original list.
1082 # (quote, (aggregate, stack)) = S
1083 # results = list_to_stack([
1084 # joy((term, stack), quote, dictionary)[0][0]
1085 # for term in iter_stack(aggregate)
1087 # return (results, stack), expression, dictionary
1088 (quote, (aggregate, stack)) = S
1090 return (aggregate, stack), expression, dictionary
1092 for term in iter_stack(aggregate):
1094 batch = (s, (quote, (S_infra, (S_first, batch))))
1095 stack = (batch, ((), stack))
1096 return stack, (S_infra, expression), dictionary
1099 #def cleave(S, expression, dictionary):
1101 # The cleave combinator expects two quotations, and below that an item X.
1102 # It first executes [P], with X on top, and saves the top result element.
1103 # Then it executes [Q], again with X, and saves the top result.
1104 # Finally it restores the stack to what it was below X and pushes the two
1105 # results P(X) and Q(X).
1107 # (Q, (P, (x, stack))) = S
1108 # p = joy((x, stack), P, dictionary)[0][0]
1109 # q = joy((x, stack), Q, dictionary)[0][0]
1110 # return (q, (p, stack)), expression, dictionary
1115 def branch(stack, expression, dictionary):
1117 Use a Boolean value to select one of two quoted programs to run.
1121 branch == roll< choice i
1125 False [F] [T] branch
1126 --------------------------
1130 -------------------------
1134 (then, (else_, (flag, stack))) = stack
1135 return stack, concat(then if flag else else_, expression), dictionary
1140 def ifte(stack, expression, dictionary):
1142 If-Then-Else Combinator
1145 ... [if] [then] [else] ifte
1146 ---------------------------------------------------
1147 ... [[else] [then]] [...] [if] infra select i
1152 ... [if] [then] [else] ifte
1153 -------------------------------------------------------
1154 ... [else] [then] [...] [if] infra first choice i
1157 Has the effect of grabbing a copy of the stack on which to run the
1158 if-part using infra.
1160 (else_, (then, (if_, stack))) = stack
1161 expression = (S_infra, (S_first, (S_choice, (S_i, expression))))
1162 stack = (if_, (stack, (then, (else_, stack))))
1163 return stack, expression, dictionary
1168 def cond(stack, expression, dictionary):
1170 This combinator works like a case statement. It expects a single quote
1171 on the stack that must contain zero or more condition quotes and a
1172 default quote. Each condition clause should contain a quoted predicate
1173 followed by the function expression to run if that predicate returns
1174 true. If no predicates return true the default function runs.
1176 It works by rewriting into a chain of nested `ifte` expressions, e.g.::
1178 [[[B0] T0] [[B1] T1] [D]] cond
1179 -----------------------------------------
1180 [B0] [T0] [[B1] [T1] [D] ifte] ifte
1183 conditions, stack = stack
1185 expression = _cond(conditions, expression)
1187 # Attempt to preload the args to first ifte.
1188 (P, (T, (E, expression))) = expression
1190 # If, for any reason, the argument to cond should happen to contain
1191 # only the default clause then this optimization will fail.
1194 stack = (E, (T, (P, stack)))
1195 return stack, expression, dictionary
1198 def _cond(conditions, expression):
1199 (clause, rest) = conditions
1200 if not rest: # clause is [D]
1203 return (P, (T, (_cond(rest, ()), (S_ifte, expression))))
1208 def dip(stack, expression, dictionary):
1210 The dip combinator expects a quoted program on the stack and below it
1211 some item, it hoists the item into the expression and runs the program
1212 on the rest of the stack.
1220 (quote, (x, stack)) = stack
1221 expression = (x, expression)
1222 return stack, concat(quote, expression), dictionary
1227 def dipd(S, expression, dictionary):
1229 Like dip but expects two items.
1233 ---------------------
1237 (quote, (x, (y, stack))) = S
1238 expression = (y, (x, expression))
1239 return stack, concat(quote, expression), dictionary
1244 def dipdd(S, expression, dictionary):
1246 Like dip but expects three items.
1250 -----------------------
1254 (quote, (x, (y, (z, stack)))) = S
1255 expression = (z, (y, (x, expression)))
1256 return stack, concat(quote, expression), dictionary
1261 def app1(S, expression, dictionary):
1263 Given a quoted program on TOS and anything as the second stack item run
1264 the program and replace the two args with the first result of the
1269 -----------------------------------
1270 ... [x ...] [Q] . infra first
1272 (quote, (x, stack)) = S
1273 stack = (quote, ((x, stack), stack))
1274 expression = (S_infra, (S_first, expression))
1275 return stack, expression, dictionary
1280 def app2(S, expression, dictionary):
1281 '''Like app1 with two items.
1285 -----------------------------------
1286 ... [y ...] [Q] . infra first
1287 [x ...] [Q] infra first
1290 (quote, (x, (y, stack))) = S
1291 expression = (S_infra, (S_first,
1292 ((x, stack), (quote, (S_infra, (S_first,
1294 stack = (quote, ((y, stack), stack))
1295 return stack, expression, dictionary
1300 def app3(S, expression, dictionary):
1301 '''Like app1 with three items.
1304 ... z y x [Q] . app3
1305 -----------------------------------
1306 ... [z ...] [Q] . infra first
1307 [y ...] [Q] infra first
1308 [x ...] [Q] infra first
1311 (quote, (x, (y, (z, stack)))) = S
1312 expression = (S_infra, (S_first,
1313 ((y, stack), (quote, (S_infra, (S_first,
1314 ((x, stack), (quote, (S_infra, (S_first,
1315 expression))))))))))
1316 stack = (quote, ((z, stack), stack))
1317 return stack, expression, dictionary
1322 def step(S, expression, dictionary):
1324 Run a quoted program on each item in a sequence.
1328 -----------------------
1333 ------------------------
1337 ... [a b c] [Q] . step
1338 ----------------------------------------
1339 ... a . Q [b c] [Q] step
1341 The step combinator executes the quotation on each member of the list
1342 on top of the stack.
1344 (quote, (aggregate, stack)) = S
1346 return stack, expression, dictionary
1347 head, tail = aggregate
1348 stack = quote, (head, stack)
1350 expression = tail, (quote, (S_step, expression))
1351 expression = S_i, expression
1352 return stack, expression, dictionary
1357 def times(stack, expression, dictionary):
1359 times == [-- dip] cons [swap] infra [0 >] swap while pop
1363 --------------------- w/ n <= 0
1368 ---------------------------------
1373 --------------------------------- w/ n > 1
1374 ... . Q (n - 1) [Q] times
1377 # times == [-- dip] cons [swap] infra [0 >] swap while pop
1378 (quote, (n, stack)) = stack
1380 return stack, expression, dictionary
1383 expression = n, (quote, (S_times, expression))
1384 expression = concat(quote, expression)
1385 return stack, expression, dictionary
1388 # The current definition above works like this:
1391 # --------------------------------------
1392 # [P] nullary [Q [P] nullary] loop
1394 # while == [pop i not] [popop] [dudipd] primrec
1396 #def while_(S, expression, dictionary):
1397 # '''[if] [body] while'''
1398 # (body, (if_, stack)) = S
1399 # while joy(stack, if_, dictionary)[0][0]:
1400 # stack = joy(stack, body, dictionary)[0]
1401 # return stack, expression, dictionary
1406 def loop(stack, expression, dictionary):
1408 Basic loop combinator.
1412 -----------------------
1416 ------------------------
1420 quote, (flag, stack) = stack
1422 expression = concat(quote, (quote, (S_loop, expression)))
1423 return stack, expression, dictionary
1428 def cmp_(stack, expression, dictionary):
1430 cmp takes two values and three quoted programs on the stack and runs
1431 one of the three depending on the results of comparing the two values:
1435 ------------------------- a > b
1439 ------------------------- a = b
1443 ------------------------- a < b
1446 L, (E, (G, (b, (a, stack)))) = stack
1447 expression = concat(G if a > b else L if a < b else E, expression)
1448 return stack, expression, dictionary
1451 #def nullary(S, expression, dictionary):
1453 # Run the program on TOS and return its first result without consuming
1454 # any of the stack (except the program on TOS.)
1456 # (quote, stack) = S
1457 # result = joy(stack, quote, dictionary)
1458 # return (result[0][0], stack), expression, dictionary
1461 #def unary(S, expression, dictionary):
1462 # (quote, stack) = S
1463 # _, return_stack = stack
1464 # result = joy(stack, quote, dictionary)[0]
1465 # return (result[0], return_stack), expression, dictionary
1468 #def binary(S, expression, dictionary):
1469 # (quote, stack) = S
1470 # _, (_, return_stack) = stack
1471 # result = joy(stack, quote, dictionary)[0]
1472 # return (result[0], return_stack), expression, dictionary
1475 #def ternary(S, expression, dictionary):
1476 # (quote, stack) = S
1477 # _, (_, (_, return_stack)) = stack
1478 # result = joy(stack, quote, dictionary)[0]
1479 # return (result[0], return_stack), expression, dictionary
1482 # FunctionWrapper(binary),
1483 # FunctionWrapper(cleave),
1484 # FunctionWrapper(nullary),
1485 # FunctionWrapper(ternary),
1486 # FunctionWrapper(unary),
1487 # FunctionWrapper(while_),
1491 BinaryBuiltinWrapper(operator.add),
1492 BinaryBuiltinWrapper(operator.and_),
1493 BinaryBuiltinWrapper(operator.div),
1494 BinaryBuiltinWrapper(operator.eq),
1495 BinaryBuiltinWrapper(operator.floordiv),
1496 BinaryBuiltinWrapper(operator.ge),
1497 BinaryBuiltinWrapper(operator.gt),
1498 BinaryBuiltinWrapper(operator.le),
1499 BinaryBuiltinWrapper(operator.lshift),
1500 BinaryBuiltinWrapper(operator.lt),
1501 BinaryBuiltinWrapper(operator.mod),
1502 BinaryBuiltinWrapper(operator.mul),
1503 BinaryBuiltinWrapper(operator.ne),
1504 BinaryBuiltinWrapper(operator.or_),
1505 BinaryBuiltinWrapper(operator.pow),
1506 BinaryBuiltinWrapper(operator.rshift),
1507 BinaryBuiltinWrapper(operator.sub),
1508 BinaryBuiltinWrapper(operator.truediv),
1509 BinaryBuiltinWrapper(operator.xor),
1511 UnaryBuiltinWrapper(abs),
1512 UnaryBuiltinWrapper(bool),
1513 UnaryBuiltinWrapper(floor),
1514 UnaryBuiltinWrapper(operator.neg),
1515 UnaryBuiltinWrapper(operator.not_),
1516 UnaryBuiltinWrapper(sqrt),
1519 del F # Otherwise Sphinx autodoc will pick it up.
1522 add_aliases(_dictionary, ALIASES)
1525 DefinitionWrapper.add_definitions(definitions, _dictionary)