1 # -*- coding: utf-8 -*-
3 # Copyright © 2014-2020 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, getmembers, isfunction
27 from functools import wraps
28 from itertools import count
31 from .parser import text_to_expression, Symbol
32 from .utils import generated_library as genlib
33 from .utils.stack import (
52 # This is the main dict we're building.
56 def inscribe(function):
57 '''A decorator to inscribe functions into the default dictionary.'''
58 _dictionary[function.name] = function
63 '''Return a dictionary of Joy functions for use with joy().'''
64 return _dictionary.copy()
72 ('floordiv', ['/floor', '//']),
73 ('truediv', ['/', 'div']),
74 ('mod', ['%', 'rem', 'remainder', 'modulus']),
77 ('getitem', ['pick', 'at']),
88 ('rolldown', ['roll<']),
89 ('rollup', ['roll>']),
95 def add_aliases(D, A):
97 Given a dict and a iterable of (name, [alias, ...]) pairs, create
98 additional entries in the dict mapping each alias to the named function
99 if it's in the dict. Aliases for functions not in the dict are ignored.
101 for name, aliases in A:
106 for alias in aliases:
112 *fraction == [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons
113 *fraction0 == concat [[swap] dip * [*] dip] infra
114 anamorphism == [pop []] swap [dip swons] genrec
115 average == [sum 1.0 *] [size] cleave /
116 binary == nullary [popop] dip
117 cleave == fork [popd] dip
118 codireco == cons dip rest cons
119 dinfrirst == dip infra first
120 unstack == ? [uncons ?] loop pop
121 down_to_zero == [0 >] [dup --] while
123 enstacken == stack [clear] dip
124 flatten == [] swap [concat] step
126 gcd == 1 [tuck modulus dup 0 >] loop pop
127 ifte == [nullary not] dipd branch
129 least_fraction == dup [gcd] infra [div] concat map
130 make_generator == [codireco] ccons
131 nullary == [stack] dinfrirst
134 tailrec == [i] genrec
135 product == 1 swap [*] step
137 range == [0 <=] [1 - dup] anamorphism
138 range_to_zero == unit [down_to_zero] infra
140 size == 0 swap [pop ++] step
142 step_zero == 0 roll> step
143 swoncat == swap concat
144 tailrec == [i] genrec
145 ternary == unary [popop] dip
146 unary == nullary popd
148 while == swap [nullary] cons dup dipd concat loop
152 # ifte == [nullary] dipd swap branch
153 # genrec == [[genrec] cons cons cons cons] nullary swons concat ifte
155 # Another definition for while. FWIW
156 # while == over [[i] dip nullary] ccons [nullary] dip loop
160 ##second == rest first
161 ##third == rest rest first
165 ##z-down == [] swap uncons swap
166 ##z-up == swons swap shunt
167 ##z-right == [swons] cons dip uncons swap
168 ##z-left == swons [uncons swap] dip swap
171 ##divisor == popop 2 *
173 ##radical == swap dup * rollup * 4 * - sqrt
176 ##q0 == [[divisor] [minusb] [radical]] pam
177 ##q1 == [[root1] [root2]] pam
178 ##quadratic == [q0] ternary i [q1] ternary
182 ##PE1.1 == + dup [+] dip
183 ##PE1.2 == dup [3 & PE1.1] dip 2 >>
184 ##PE1.3 == 14811 swap [PE1.2] times pop
185 ##PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop
187 #PE1.2 == [PE1.1] step
188 #PE1 == 0 0 66 [[3 2 1 3 1 2 3] PE1.2] times [3 2 1 3] PE1.2 pop
192 class NotAnIntError(Exception): pass
193 class StackUnderflowError(Exception): pass
196 def FunctionWrapper(f):
197 '''Set name attribute.'''
199 raise ValueError('Function %s must have doc string.' % f.__name__)
200 f.name = f.__name__.rstrip('_') # Don't shadow builtins.
204 def SimpleFunctionWrapper(f):
206 Wrap functions that take and return just a stack.
210 def inner(stack, expression, dictionary):
211 return f(stack), expression, dictionary
215 def BinaryBuiltinWrapper(f):
217 Wrap functions that take two arguments and return a single result.
221 def inner(stack, expression, dictionary):
223 (a, (b, stack)) = stack
225 raise StackUnderflowError
226 if not isinstance(a, int) or not isinstance(b, int):
229 return (result, stack), expression, dictionary
233 def UnaryBuiltinWrapper(f):
235 Wrap functions that take one argument and return a single result.
239 def inner(stack, expression, dictionary):
242 return (result, stack), expression, dictionary
246 class DefinitionWrapper(object):
248 Provide implementation of defined functions, and some helper methods.
251 def __init__(self, name, body_text, doc=None):
252 self.name = self.__name__ = name
253 self.body = text_to_expression(body_text)
254 self._body = tuple(iter_stack(self.body))
255 self.__doc__ = doc or body_text
256 self._compiled = None
258 def __call__(self, stack, expression, dictionary):
260 return self._compiled(stack, expression, dictionary) # pylint: disable=E1102
261 expression = list_to_stack(self._body, expression)
262 return stack, expression, dictionary
265 def parse_definition(class_, defi):
267 Given some text describing a Joy function definition parse it and
268 return a DefinitionWrapper.
270 # At some point I decided that the definitions file should NOT
271 # use '==' to separate the name from the body. But somehow the
272 # xerblin\gui\default_joy_home\definitions.txt file didn't get
273 # the memo. Nor did the load_definitions() method.
274 # So I think the simplest way forward at the moment will be to
275 # edit this function to expect '=='.
277 name, part, body = defi.partition('==')
279 return class_(name.strip(), body.strip())
280 raise ValueError("No '==' in definition text %r" % (defi,))
282 # return class_(*(n.strip() for n in defi.split(None, 1)))
285 def add_definitions(class_, defs, dictionary):
287 Scan multi-line string defs for definitions and add them to the
290 for definition in _text_to_defs(defs):
291 class_.add_def(definition, dictionary)
294 def add_def(class_, definition, dictionary, fail_fails=False):
296 Add the definition to the dictionary.
298 F = class_.parse_definition(definition)
299 dictionary[F.name] = F
302 def load_definitions(class_, filename, dictionary):
303 with open(filename) as f:
304 lines = [line for line in f if '==' in line]
306 class_.add_def(line, dictionary)
309 def _text_to_defs(text):
312 for line in text.splitlines()
314 and not line.startswith('#')
326 def inscribe_(stack, expression, dictionary):
328 Create a new Joy function definition in the Joy dictionary. A
329 definition is given as a string with a name followed by a double
330 equal sign then one or more Joy functions, the body. for example:
334 If you want the definition to persist over restarts, enter it into
335 the definitions.txt resource.
337 definition, stack = stack
338 DefinitionWrapper.add_def(definition, dictionary, fail_fails=True)
339 return stack, expression, dictionary
343 @SimpleFunctionWrapper
345 '''Parse the string on the stack to a Joy expression.'''
347 expression = text_to_expression(text)
348 return expression, stack
352 # @SimpleFunctionWrapper
354 # '''Attempt to infer the stack effect of a Joy expression.'''
356 # effects = infer_expression(E)
357 # e = list_to_stack([(fi, (fo, ())) for fi, fo in effects])
362 @SimpleFunctionWrapper
367 getitem == drop first
369 Expects an integer and a quote on the stack and returns the item at the
370 nth position in the quote counting from 0.
374 -------------------------
378 n, (Q, stack) = stack
379 return pick(Q, n), stack
383 @SimpleFunctionWrapper
390 Expects an integer and a quote on the stack and returns the quote with
391 n items removed off the top.
395 ----------------------
399 n, (Q, stack) = stack
410 @SimpleFunctionWrapper
413 Expects an integer and a quote on the stack and returns the quote with
414 just the top n items in reverse order (because that's easier and you can
415 use reverse if needed.)
419 ----------------------
423 n, (Q, stack) = stack
436 @SimpleFunctionWrapper
439 Use a Boolean value to select one of two items.
443 ----------------------
448 ---------------------
451 Currently Python semantics are used to evaluate the "truthiness" of the
452 Boolean value (so empty string, zero, etc. are counted as false, etc.)
454 (if_, (then, (else_, stack))) = stack
455 return then if if_ else else_, stack
459 @SimpleFunctionWrapper
462 Use a Boolean value to select one of two items from a sequence.
466 ------------------------
471 -----------------------
474 The sequence can contain more than two items but not fewer.
475 Currently Python semantics are used to evaluate the "truthiness" of the
476 Boolean value (so empty string, zero, etc. are counted as false, etc.)
478 (flag, (choices, stack)) = stack
479 (else_, (then, _)) = choices
480 return then if flag else else_, stack
484 @SimpleFunctionWrapper
486 '''Given a list find the maximum.'''
488 return max(iter_stack(tos)), stack
492 @SimpleFunctionWrapper
494 '''Given a list find the minimum.'''
496 return min(iter_stack(tos)), stack
500 @SimpleFunctionWrapper
503 Given a quoted sequence of numbers return the sum.
506 sum == 0 swap [+] step
510 return sum(iter_stack(tos)), stack
514 @SimpleFunctionWrapper
517 Expects an item on the stack and a quote under it and removes that item
518 from the the quote. The item is only removed once.
522 ------------------------
526 (tos, (second, stack)) = S
527 l = list(iter_stack(second))
529 return list_to_stack(l), stack
533 @SimpleFunctionWrapper
535 '''Given a list remove duplicate items.'''
537 I = list(iter_stack(tos))
538 return list_to_stack(sorted(set(I), key=I.index)), stack
542 @SimpleFunctionWrapper
544 '''Given a list return it sorted.'''
546 return list_to_stack(sorted(iter_stack(tos))), stack
550 @SimpleFunctionWrapper
552 '''Clear everything from the stack.
555 clear == stack [pop stack] loop
565 @SimpleFunctionWrapper
566 def disenstacken(stack):
568 The disenstacken operator expects a list on top of the stack and makes that
569 the stack discarding the rest of the stack.
575 @SimpleFunctionWrapper
578 Reverse the list on the top of the stack.
581 reverse == [] swap shunt
585 for term in iter_stack(tos):
591 @SimpleFunctionWrapper
594 Concatinate the two lists on the top of the stack.
597 [a b c] [d e f] concat
598 ----------------------------
602 (tos, (second, stack)) = S
603 return concat(second, tos), stack
607 @SimpleFunctionWrapper
610 Like concat but reverses the top list into the second.
613 shunt == [swons] step == reverse swap concat
615 [a b c] [d e f] shunt
616 ---------------------------
620 (tos, (second, stack)) = stack
623 second = term, second
628 @SimpleFunctionWrapper
631 Replace the two lists on the top of the stack with a list of the pairs
632 from each list. The smallest list sets the length of the result list.
634 (tos, (second, stack)) = S
637 for a, b in zip(iter_stack(tos), iter_stack(second))
639 return list_to_stack(accumulator), stack
643 @SimpleFunctionWrapper
647 return tos + 1, stack
651 @SimpleFunctionWrapper
655 return tos - 1, stack
659 @SimpleFunctionWrapper
670 a, (b, stack) = stack
676 return int(math.floor(n))
678 floor.__doc__ = math.floor.__doc__
682 @SimpleFunctionWrapper
685 divmod(x, y) -> (quotient, remainder)
687 Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
696 Return the square root of the number a.
697 Negative numbers return complex roots.
702 assert a < 0, repr(a)
703 r = math.sqrt(-a) * 1j
709 # if isinstance(text, str):
710 # return run(text, stack)
715 @SimpleFunctionWrapper
717 '''The identity function.'''
722 @SimpleFunctionWrapper
724 '''True if the form on TOS is void otherwise False.'''
726 return _void(form), stack
730 return any(not _void(i) for i in iter_stack(form))
741 def words(stack, expression, dictionary):
742 '''Print all the words in alphabetical order.'''
743 print(' '.join(sorted(dictionary)))
744 return stack, expression, dictionary
749 def sharing(stack, expression, dictionary):
750 '''Print redistribution information.'''
751 print("You may convey verbatim copies of the Program's source code as"
752 ' you receive it, in any medium, provided that you conspicuously'
753 ' and appropriately publish on each copy an appropriate copyright'
754 ' notice; keep intact all notices stating that this License and'
755 ' any non-permissive terms added in accord with section 7 apply'
756 ' to the code; keep intact all notices of the absence of any'
757 ' warranty; and give all recipients a copy of this License along'
759 ' You should have received a copy of the GNU General Public License'
760 ' along with Thun. If not see <http://www.gnu.org/licenses/>.')
761 return stack, expression, dictionary
766 def warranty(stack, expression, dictionary):
767 '''Print warranty information.'''
768 print('THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY'
769 ' APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE'
770 ' COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM'
771 ' "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR'
772 ' IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES'
773 ' OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE'
774 ' ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS'
775 ' WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE'
776 ' COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.')
777 return stack, expression, dictionary
780 # def simple_manual(stack):
782 # Print words and help for each word.
784 # for name, f in sorted(FUNCTIONS.items()):
786 # boxline = '+%s+' % ('-' * (len(name) + 2))
789 # '| %s |' % (name,),
791 # d if d else ' ...',
801 def help_(S, expression, dictionary):
802 '''Accepts a quoted symbol on the top of the stack and prints its docs.'''
803 ((symbol, _), stack) = S
804 word = dictionary[symbol]
805 print(HELP_TEMPLATE % (symbol, getdoc(word), symbol))
806 return stack, expression, dictionary
814 # Several combinators depend on other words in their definitions,
815 # we use symbols to prevent hard-coding these, so in theory, you
816 # could change the word in the dictionary to use different semantics.
817 S_choice = Symbol('choice')
818 S_first = Symbol('first')
819 S_genrec = Symbol('genrec')
820 S_getitem = Symbol('getitem')
822 S_ifte = Symbol('ifte')
823 S_infra = Symbol('infra')
824 S_loop = Symbol('loop')
825 S_pop = Symbol('pop')
826 S_primrec = Symbol('primrec')
827 S_step = Symbol('step')
828 S_swaack = Symbol('swaack')
829 S_times = Symbol('times')
834 def i(stack, expression, dictionary):
836 The i combinator expects a quoted program on the stack and unpacks it
837 onto the pending expression for evaluation.
846 return stack, concat(quote, expression), dictionary
851 def x(stack, expression, dictionary):
857 ... [Q] x = ... [Q] dup i
858 ... [Q] x = ... [Q] [Q] i
859 ... [Q] x = ... [Q] Q
863 return stack, concat(quote, expression), dictionary
868 def b(stack, expression, dictionary):
874 ... [P] [Q] b == ... [P] i [Q] i
875 ... [P] [Q] b == ... P Q
878 q, (p, (stack)) = stack
879 return stack, concat(p, concat(q, expression)), dictionary
884 def dupdip(stack, expression, dictionary):
888 [F] dupdip == dup [F] dip
898 return stack, concat(F, (a, expression)), dictionary
903 def infra(stack, expression, dictionary):
905 Accept a quoted program and a list on the stack and run the program
906 with the list as its stack. Does not affect the rest of the stack.
909 ... [a b c] [Q] . infra
910 -----------------------------
911 c b a . Q [...] swaack
914 (quote, (aggregate, stack)) = stack
915 return aggregate, concat(quote, (stack, (S_swaack, expression))), dictionary
920 def genrec(stack, expression, dictionary):
922 General Recursion Combinator.
925 [if] [then] [rec1] [rec2] genrec
926 ---------------------------------------------------------------------
927 [if] [then] [rec1 [[if] [then] [rec1] [rec2] genrec] rec2] ifte
929 From "Recursion Theory and Joy" (j05cmp.html) by Manfred von Thun:
930 "The genrec combinator takes four program parameters in addition to
931 whatever data parameters it needs. Fourth from the top is an if-part,
932 followed by a then-part. If the if-part yields true, then the then-part
933 is executed and the combinator terminates. The other two parameters are
934 the rec1-part and the rec2-part. If the if-part yields false, the
935 rec1-part is executed. Following that the four program parameters and
936 the combinator are again pushed onto the stack bundled up in a quoted
937 form. Then the rec2-part is executed, where it will find the bundled
938 form. Typically it will then execute the bundled form, either with i or
939 with app2, or some other combinator."
941 The way to design one of these is to fix your base case [then] and the
942 test [if], and then treat rec1 and rec2 as an else-part "sandwiching"
943 a quotation of the whole function.
945 For example, given a (general recursive) function 'F':
948 F == [I] [T] [R1] [R2] genrec
950 If the [I] if-part fails you must derive R1 and R2 from:
955 Just set the stack arguments in front, and figure out what R1 and R2
956 have to do to apply the quoted [F] in the proper way. In effect, the
957 genrec combinator turns into an ifte combinator with a quoted copy of
958 the original definition in the else-part:
961 F == [I] [T] [R1] [R2] genrec
962 == [I] [T] [R1 [F] R2] ifte
964 Primitive recursive functions are those where R2 == i.
967 P == [I] [T] [R] tailrec
968 == [I] [T] [R [P] i] ifte
969 == [I] [T] [R P] ifte
972 (rec2, (rec1, stack)) = stack
973 (then, (if_, _)) = stack
974 F = (if_, (then, (rec1, (rec2, (S_genrec, ())))))
975 else_ = concat(rec1, (F, rec2))
976 return (else_, stack), (S_ifte, expression), dictionary
981 def map_(S, expression, dictionary):
983 Run the quoted program on TOS on the items in the list under it, push a
984 new list with the results in place of the program and original list.
986 # (quote, (aggregate, stack)) = S
987 # results = list_to_stack([
988 # joy((term, stack), quote, dictionary)[0][0]
989 # for term in iter_stack(aggregate)
991 # return (results, stack), expression, dictionary
992 (quote, (aggregate, stack)) = S
994 return (aggregate, stack), expression, dictionary
996 for term in iter_stack(aggregate):
998 batch = (s, (quote, (S_infra, (S_first, batch))))
999 stack = (batch, ((), stack))
1000 return stack, (S_infra, expression), dictionary
1005 def primrec(stack, expression, dictionary):
1007 From the "Overview of the language JOY":
1009 > The primrec combinator expects two quoted programs in addition to a
1010 data parameter. For an integer data parameter it works like this: If
1011 the data parameter is zero, then the first quotation has to produce
1012 the value to be returned. If the data parameter is positive then the
1013 second has to combine the data parameter with the result of applying
1014 the function to its predecessor.::
1018 > Then primrec tests whether the top element on the stack (initially
1019 the 5) is equal to zero. If it is, it pops it off and executes one of
1020 the quotations, the [1] which leaves 1 on the stack as the result.
1021 Otherwise it pushes a decremented copy of the top element and
1022 recurses. On the way back from the recursion it uses the other
1023 quotation, [*], to multiply what is now a factorial on top of the
1024 stack by the second element on the stack.::
1026 n [Base] [Recur] primrec
1028 0 [Base] [Recur] primrec
1029 ------------------------------
1032 n [Base] [Recur] primrec
1033 ------------------------------------------ n > 0
1034 n (n-1) [Base] [Recur] primrec Recur
1037 recur, (base, (n, stack)) = stack
1039 expression = concat(base, expression)
1041 expression = S_primrec, concat(recur, expression)
1042 stack = recur, (base, (n - 1, (n, stack)))
1043 return stack, expression, dictionary
1046 #def cleave(S, expression, dictionary):
1048 # The cleave combinator expects two quotations, and below that an item X.
1049 # It first executes [P], with X on top, and saves the top result element.
1050 # Then it executes [Q], again with X, and saves the top result.
1051 # Finally it restores the stack to what it was below X and pushes the two
1052 # results P(X) and Q(X).
1054 # (Q, (P, (x, stack))) = S
1055 # p = joy((x, stack), P, dictionary)[0][0]
1056 # q = joy((x, stack), Q, dictionary)[0][0]
1057 # return (q, (p, stack)), expression, dictionary
1062 def branch(stack, expression, dictionary):
1064 Use a Boolean value to select one of two quoted programs to run.
1068 branch == roll< choice i
1072 False [F] [T] branch
1073 --------------------------
1077 -------------------------
1081 (then, (else_, (flag, stack))) = stack
1082 return stack, concat(then if flag else else_, expression), dictionary
1087 ##def ifte(stack, expression, dictionary):
1089 ## If-Then-Else Combinator
1092 ## ... [if] [then] [else] ifte
1093 ## ---------------------------------------------------
1094 ## ... [[else] [then]] [...] [if] infra select i
1099 ## ... [if] [then] [else] ifte
1100 ## -------------------------------------------------------
1101 ## ... [else] [then] [...] [if] infra first choice i
1104 ## Has the effect of grabbing a copy of the stack on which to run the
1105 ## if-part using infra.
1107 ## (else_, (then, (if_, stack))) = stack
1108 ## expression = (S_infra, (S_first, (S_choice, (S_i, expression))))
1109 ## stack = (if_, (stack, (then, (else_, stack))))
1110 ## return stack, expression, dictionary
1115 def cond(stack, expression, dictionary):
1117 This combinator works like a case statement. It expects a single quote
1118 on the stack that must contain zero or more condition quotes and a
1119 default quote. Each condition clause should contain a quoted predicate
1120 followed by the function expression to run if that predicate returns
1121 true. If no predicates return true the default function runs.
1123 It works by rewriting into a chain of nested `ifte` expressions, e.g.::
1125 [[[B0] T0] [[B1] T1] [D]] cond
1126 -----------------------------------------
1127 [B0] [T0] [[B1] [T1] [D] ifte] ifte
1130 conditions, stack = stack
1132 expression = _cond(conditions, expression)
1134 # Attempt to preload the args to first ifte.
1135 (P, (T, (E, expression))) = expression
1137 # If, for any reason, the argument to cond should happen to contain
1138 # only the default clause then this optimization will fail.
1141 stack = (E, (T, (P, stack)))
1142 return stack, expression, dictionary
1145 def _cond(conditions, expression):
1146 (clause, rest) = conditions
1147 if not rest: # clause is [D]
1150 return (P, (T, (_cond(rest, ()), (S_ifte, expression))))
1155 def dip(stack, expression, dictionary):
1157 The dip combinator expects a quoted program on the stack and below it
1158 some item, it hoists the item into the expression and runs the program
1159 on the rest of the stack.
1167 (quote, (x, stack)) = stack
1168 expression = (x, expression)
1169 return stack, concat(quote, expression), dictionary
1174 def dipd(S, expression, dictionary):
1176 Like dip but expects two items.
1180 ---------------------
1184 (quote, (x, (y, stack))) = S
1185 expression = (y, (x, expression))
1186 return stack, concat(quote, expression), dictionary
1191 def dipdd(S, expression, dictionary):
1193 Like dip but expects three items.
1197 -----------------------
1201 (quote, (x, (y, (z, stack)))) = S
1202 expression = (z, (y, (x, expression)))
1203 return stack, concat(quote, expression), dictionary
1208 def app1(S, expression, dictionary):
1210 Given a quoted program on TOS and anything as the second stack item run
1211 the program and replace the two args with the first result of the
1216 -----------------------------------
1217 ... [x ...] [Q] . infra first
1220 (quote, (x, stack)) = S
1221 stack = (quote, ((x, stack), stack))
1222 expression = (S_infra, (S_first, expression))
1223 return stack, expression, dictionary
1228 def app2(S, expression, dictionary):
1229 '''Like app1 with two items.
1233 -----------------------------------
1234 ... [y ...] [Q] . infra first
1235 [x ...] [Q] infra first
1238 (quote, (x, (y, stack))) = S
1239 expression = (S_infra, (S_first,
1240 ((x, stack), (quote, (S_infra, (S_first,
1242 stack = (quote, ((y, stack), stack))
1243 return stack, expression, dictionary
1248 def app3(S, expression, dictionary):
1249 '''Like app1 with three items.
1252 ... z y x [Q] . app3
1253 -----------------------------------
1254 ... [z ...] [Q] . infra first
1255 [y ...] [Q] infra first
1256 [x ...] [Q] infra first
1259 (quote, (x, (y, (z, stack)))) = S
1260 expression = (S_infra, (S_first,
1261 ((y, stack), (quote, (S_infra, (S_first,
1262 ((x, stack), (quote, (S_infra, (S_first,
1263 expression))))))))))
1264 stack = (quote, ((z, stack), stack))
1265 return stack, expression, dictionary
1270 def step(S, expression, dictionary):
1272 Run a quoted program on each item in a sequence.
1276 -----------------------
1281 ------------------------
1285 ... [a b c] [Q] . step
1286 ----------------------------------------
1287 ... a . Q [b c] [Q] step
1289 The step combinator executes the quotation on each member of the list
1290 on top of the stack.
1292 (quote, (aggregate, stack)) = S
1294 return stack, expression, dictionary
1295 head, tail = aggregate
1296 stack = quote, (head, stack)
1298 expression = tail, (quote, (S_step, expression))
1299 expression = S_i, expression
1300 return stack, expression, dictionary
1305 def times(stack, expression, dictionary):
1307 times == [-- dip] cons [swap] infra [0 >] swap while pop
1311 --------------------- w/ n <= 0
1316 -----------------------
1321 ------------------------------------- w/ n > 1
1322 ... . Q (n - 1) [Q] times
1325 # times == [-- dip] cons [swap] infra [0 >] swap while pop
1326 (quote, (n, stack)) = stack
1328 return stack, expression, dictionary
1331 expression = n, (quote, (S_times, expression))
1332 expression = concat(quote, expression)
1333 return stack, expression, dictionary
1336 # The current definition above works like this:
1339 # --------------------------------------
1340 # [P] nullary [Q [P] nullary] loop
1342 # while == [pop i not] [popop] [dudipd] tailrec
1344 #def while_(S, expression, dictionary):
1345 # '''[if] [body] while'''
1346 # (body, (if_, stack)) = S
1347 # while joy(stack, if_, dictionary)[0][0]:
1348 # stack = joy(stack, body, dictionary)[0]
1349 # return stack, expression, dictionary
1354 def loop(stack, expression, dictionary):
1356 Basic loop combinator.
1360 -----------------------
1364 ------------------------
1368 quote, (flag, stack) = stack
1370 expression = concat(quote, (quote, (S_loop, expression)))
1371 return stack, expression, dictionary
1376 def cmp_(stack, expression, dictionary):
1378 cmp takes two values and three quoted programs on the stack and runs
1379 one of the three depending on the results of comparing the two values:
1383 ------------------------- a > b
1387 ------------------------- a = b
1391 ------------------------- a < b
1394 L, (E, (G, (b, (a, stack)))) = stack
1395 expression = concat(G if a > b else L if a < b else E, expression)
1396 return stack, expression, dictionary
1399 # FunctionWrapper(cleave),
1400 # FunctionWrapper(while_),
1405 #divmod_ = pm = __(n2, n1), __(n4, n3)
1407 BinaryBuiltinWrapper(operator.eq),
1408 BinaryBuiltinWrapper(operator.ge),
1409 BinaryBuiltinWrapper(operator.gt),
1410 BinaryBuiltinWrapper(operator.le),
1411 BinaryBuiltinWrapper(operator.lt),
1412 BinaryBuiltinWrapper(operator.ne),
1414 BinaryBuiltinWrapper(operator.xor),
1415 BinaryBuiltinWrapper(operator.lshift),
1416 BinaryBuiltinWrapper(operator.rshift),
1418 BinaryBuiltinWrapper(operator.and_),
1419 BinaryBuiltinWrapper(operator.or_),
1421 BinaryBuiltinWrapper(operator.add),
1422 BinaryBuiltinWrapper(operator.floordiv),
1423 BinaryBuiltinWrapper(operator.mod),
1424 BinaryBuiltinWrapper(operator.mul),
1425 BinaryBuiltinWrapper(operator.pow),
1426 BinaryBuiltinWrapper(operator.sub),
1427 BinaryBuiltinWrapper(operator.truediv),
1429 UnaryBuiltinWrapper(bool),
1430 UnaryBuiltinWrapper(operator.not_),
1432 UnaryBuiltinWrapper(abs),
1433 UnaryBuiltinWrapper(operator.neg),
1434 UnaryBuiltinWrapper(sqrt),
1436 UnaryBuiltinWrapper(floor),
1437 UnaryBuiltinWrapper(round),
1440 del F # Otherwise Sphinx autodoc will pick it up.
1443 for name, primitive in getmembers(genlib, isfunction):
1444 inscribe(SimpleFunctionWrapper(primitive))
1447 add_aliases(_dictionary, ALIASES)
1450 DefinitionWrapper.add_definitions(definitions, _dictionary)