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.errors import NotAnIntError, StackUnderflowError
34 from .utils.stack import (
53 # This is the main dict we're building.
57 def inscribe(function):
58 '''A decorator to inscribe functions into the default dictionary.'''
59 _dictionary[function.name] = function
64 '''Return a dictionary of Joy functions for use with joy().'''
65 return _dictionary.copy()
73 ('floordiv', ['/floor', '//']),
74 ('truediv', ['/', 'div']),
75 ('mod', ['%', 'rem', 'remainder', 'modulus']),
78 ('getitem', ['pick', 'at']),
89 ('rolldown', ['roll<']),
90 ('rollup', ['roll>']),
96 def add_aliases(D, A):
98 Given a dict and a iterable of (name, [alias, ...]) pairs, create
99 additional entries in the dict mapping each alias to the named function
100 if it's in the dict. Aliases for functions not in the dict are ignored.
102 for name, aliases in A:
107 for alias in aliases:
113 *fraction == [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons
114 *fraction0 == concat [[swap] dip * [*] dip] infra
115 anamorphism == [pop []] swap [dip swons] genrec
116 average == [sum 1.0 *] [size] cleave /
117 binary == nullary [popop] dip
118 cleave == fork [popd] dip
119 codireco == cons dip rest cons
120 dinfrirst == dip infra first
121 unstack == ? [uncons ?] loop pop
122 down_to_zero == [0 >] [dup --] while
124 enstacken == stack [clear] dip
125 flatten == [] swap [concat] step
127 gcd == 1 [tuck modulus dup 0 >] loop pop
128 ifte == [nullary not] dipd branch
130 least_fraction == dup [gcd] infra [div] concat map
131 make_generator == [codireco] ccons
132 nullary == [stack] dinfrirst
135 tailrec == [i] genrec
136 product == 1 swap [*] step
138 range == [0 <=] [1 - dup] anamorphism
139 range_to_zero == unit [down_to_zero] infra
141 size == 0 swap [pop ++] step
143 step_zero == 0 roll> step
144 swoncat == swap concat
145 tailrec == [i] genrec
146 ternary == unary [popop] dip
147 unary == nullary popd
149 while == swap [nullary] cons dup dipd concat loop
153 # ifte == [nullary] dipd swap branch
154 # genrec == [[genrec] cons cons cons cons] nullary swons concat ifte
156 # Another definition for while. FWIW
157 # while == over [[i] dip nullary] ccons [nullary] dip loop
161 ##second == rest first
162 ##third == rest rest first
166 ##z-down == [] swap uncons swap
167 ##z-up == swons swap shunt
168 ##z-right == [swons] cons dip uncons swap
169 ##z-left == swons [uncons swap] dip swap
172 ##divisor == popop 2 *
174 ##radical == swap dup * rollup * 4 * - sqrt
177 ##q0 == [[divisor] [minusb] [radical]] pam
178 ##q1 == [[root1] [root2]] pam
179 ##quadratic == [q0] ternary i [q1] ternary
183 ##PE1.1 == + dup [+] dip
184 ##PE1.2 == dup [3 & PE1.1] dip 2 >>
185 ##PE1.3 == 14811 swap [PE1.2] times pop
186 ##PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop
188 #PE1.2 == [PE1.1] step
189 #PE1 == 0 0 66 [[3 2 1 3 1 2 3] PE1.2] times [3 2 1 3] PE1.2 pop
193 def FunctionWrapper(f):
194 '''Set name attribute.'''
196 raise ValueError('Function %s must have doc string.' % f.__name__)
197 f.name = f.__name__.rstrip('_') # Don't shadow builtins.
201 def SimpleFunctionWrapper(f):
203 Wrap functions that take and return just a stack.
207 def inner(stack, expression, dictionary):
208 return f(stack), expression, dictionary
212 def BinaryBuiltinWrapper(f):
214 Wrap functions that take two arguments and return a single result.
218 def inner(stack, expression, dictionary):
220 (a, (b, stack)) = stack
222 raise StackUnderflowError
223 if (not isinstance(a, int)
224 or not isinstance(b, int)
225 or isinstance(a, bool) # Because bools are ints in Python.
226 or isinstance(a, bool)
230 return (result, stack), expression, dictionary
234 def UnaryBuiltinWrapper(f):
236 Wrap functions that take one argument and return a single result.
240 def inner(stack, expression, dictionary):
243 return (result, stack), expression, dictionary
247 class DefinitionWrapper(object):
249 Provide implementation of defined functions, and some helper methods.
252 def __init__(self, name, body_text, doc=None):
253 self.name = self.__name__ = name
254 self.body = text_to_expression(body_text)
255 self._body = tuple(iter_stack(self.body))
256 self.__doc__ = doc or body_text
257 self._compiled = None
259 def __call__(self, stack, expression, dictionary):
261 return self._compiled(stack, expression, dictionary) # pylint: disable=E1102
262 expression = list_to_stack(self._body, expression)
263 return stack, expression, dictionary
266 def parse_definition(class_, defi):
268 Given some text describing a Joy function definition parse it and
269 return a DefinitionWrapper.
271 # At some point I decided that the definitions file should NOT
272 # use '==' to separate the name from the body. But somehow the
273 # xerblin\gui\default_joy_home\definitions.txt file didn't get
274 # the memo. Nor did the load_definitions() method.
275 # So I think the simplest way forward at the moment will be to
276 # edit this function to expect '=='.
278 name, part, body = defi.partition('==')
280 return class_(name.strip(), body.strip())
281 raise ValueError("No '==' in definition text %r" % (defi,))
283 # return class_(*(n.strip() for n in defi.split(None, 1)))
286 def add_definitions(class_, defs, dictionary):
288 Scan multi-line string defs for definitions and add them to the
291 for definition in _text_to_defs(defs):
292 class_.add_def(definition, dictionary)
295 def add_def(class_, definition, dictionary, fail_fails=False):
297 Add the definition to the dictionary.
299 F = class_.parse_definition(definition)
300 dictionary[F.name] = F
303 def load_definitions(class_, filename, dictionary):
304 with open(filename) as f:
305 lines = [line for line in f if '==' in line]
307 class_.add_def(line, dictionary)
310 def _text_to_defs(text):
313 for line in text.splitlines()
315 and not line.startswith('#')
327 def inscribe_(stack, expression, dictionary):
329 Create a new Joy function definition in the Joy dictionary. A
330 definition is given as a string with a name followed by a double
331 equal sign then one or more Joy functions, the body. for example:
335 If you want the definition to persist over restarts, enter it into
336 the definitions.txt resource.
338 definition, stack = stack
339 DefinitionWrapper.add_def(definition, dictionary, fail_fails=True)
340 return stack, expression, dictionary
344 @SimpleFunctionWrapper
346 '''Parse the string on the stack to a Joy expression.'''
348 expression = text_to_expression(text)
349 return expression, stack
353 # @SimpleFunctionWrapper
355 # '''Attempt to infer the stack effect of a Joy expression.'''
357 # effects = infer_expression(E)
358 # e = list_to_stack([(fi, (fo, ())) for fi, fo in effects])
363 @SimpleFunctionWrapper
368 getitem == drop first
370 Expects an integer and a quote on the stack and returns the item at the
371 nth position in the quote counting from 0.
375 -------------------------
379 n, (Q, stack) = stack
380 return pick(Q, n), stack
384 @SimpleFunctionWrapper
391 Expects an integer and a quote on the stack and returns the quote with
392 n items removed off the top.
396 ----------------------
400 n, (Q, stack) = stack
411 @SimpleFunctionWrapper
414 Expects an integer and a quote on the stack and returns the quote with
415 just the top n items in reverse order (because that's easier and you can
416 use reverse if needed.)
420 ----------------------
424 n, (Q, stack) = stack
437 @SimpleFunctionWrapper
440 Use a Boolean value to select one of two items.
444 ----------------------
449 ---------------------
452 Currently Python semantics are used to evaluate the "truthiness" of the
453 Boolean value (so empty string, zero, etc. are counted as false, etc.)
455 (if_, (then, (else_, stack))) = stack
456 return then if if_ else else_, stack
460 @SimpleFunctionWrapper
463 Use a Boolean value to select one of two items from a sequence.
467 ------------------------
472 -----------------------
475 The sequence can contain more than two items but not fewer.
476 Currently Python semantics are used to evaluate the "truthiness" of the
477 Boolean value (so empty string, zero, etc. are counted as false, etc.)
479 (flag, (choices, stack)) = stack
480 (else_, (then, _)) = choices
481 return then if flag else else_, stack
485 @SimpleFunctionWrapper
487 '''Given a list find the maximum.'''
489 return max(iter_stack(tos)), stack
493 @SimpleFunctionWrapper
495 '''Given a list find the minimum.'''
497 return min(iter_stack(tos)), stack
501 @SimpleFunctionWrapper
504 Given a quoted sequence of numbers return the sum.
507 sum == 0 swap [+] step
511 return sum(iter_stack(tos)), stack
515 @SimpleFunctionWrapper
518 Expects an item on the stack and a quote under it and removes that item
519 from the the quote. The item is only removed once.
523 ------------------------
527 (tos, (second, stack)) = S
528 l = list(iter_stack(second))
530 return list_to_stack(l), stack
534 @SimpleFunctionWrapper
536 '''Given a list remove duplicate items.'''
538 I = list(iter_stack(tos))
539 return list_to_stack(sorted(set(I), key=I.index)), stack
543 @SimpleFunctionWrapper
545 '''Given a list return it sorted.'''
547 return list_to_stack(sorted(iter_stack(tos))), stack
551 @SimpleFunctionWrapper
553 '''Clear everything from the stack.
556 clear == stack [pop stack] loop
566 @SimpleFunctionWrapper
567 def disenstacken(stack):
569 The disenstacken operator expects a list on top of the stack and makes that
570 the stack discarding the rest of the stack.
576 @SimpleFunctionWrapper
579 Reverse the list on the top of the stack.
582 reverse == [] swap shunt
586 for term in iter_stack(tos):
592 @SimpleFunctionWrapper
595 Concatinate the two lists on the top of the stack.
598 [a b c] [d e f] concat
599 ----------------------------
603 (tos, (second, stack)) = S
604 return concat(second, tos), stack
608 @SimpleFunctionWrapper
611 Like concat but reverses the top list into the second.
614 shunt == [swons] step == reverse swap concat
616 [a b c] [d e f] shunt
617 ---------------------------
621 (tos, (second, stack)) = stack
624 second = term, second
629 @SimpleFunctionWrapper
632 Replace the two lists on the top of the stack with a list of the pairs
633 from each list. The smallest list sets the length of the result list.
635 (tos, (second, stack)) = S
638 for a, b in zip(iter_stack(tos), iter_stack(second))
640 return list_to_stack(accumulator), stack
644 @SimpleFunctionWrapper
648 return tos + 1, stack
652 @SimpleFunctionWrapper
656 return tos - 1, stack
660 @SimpleFunctionWrapper
671 a, (b, stack) = stack
677 return int(math.floor(n))
679 floor.__doc__ = math.floor.__doc__
683 @SimpleFunctionWrapper
686 divmod(x, y) -> (quotient, remainder)
688 Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
697 Return the square root of the number a.
698 Negative numbers return complex roots.
703 assert a < 0, repr(a)
704 r = math.sqrt(-a) * 1j
710 # if isinstance(text, str):
711 # return run(text, stack)
716 @SimpleFunctionWrapper
718 '''The identity function.'''
723 @SimpleFunctionWrapper
725 '''True if the form on TOS is void otherwise False.'''
727 return _void(form), stack
731 return any(not _void(i) for i in iter_stack(form))
742 def words(stack, expression, dictionary):
743 '''Print all the words in alphabetical order.'''
744 print(' '.join(sorted(dictionary)))
745 return stack, expression, dictionary
750 def sharing(stack, expression, dictionary):
751 '''Print redistribution information.'''
752 print("You may convey verbatim copies of the Program's source code as"
753 ' you receive it, in any medium, provided that you conspicuously'
754 ' and appropriately publish on each copy an appropriate copyright'
755 ' notice; keep intact all notices stating that this License and'
756 ' any non-permissive terms added in accord with section 7 apply'
757 ' to the code; keep intact all notices of the absence of any'
758 ' warranty; and give all recipients a copy of this License along'
760 ' You should have received a copy of the GNU General Public License'
761 ' along with Thun. If not see <http://www.gnu.org/licenses/>.')
762 return stack, expression, dictionary
767 def warranty(stack, expression, dictionary):
768 '''Print warranty information.'''
769 print('THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY'
770 ' APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE'
771 ' COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM'
772 ' "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR'
773 ' IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES'
774 ' OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE'
775 ' ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS'
776 ' WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE'
777 ' COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.')
778 return stack, expression, dictionary
781 # def simple_manual(stack):
783 # Print words and help for each word.
785 # for name, f in sorted(FUNCTIONS.items()):
787 # boxline = '+%s+' % ('-' * (len(name) + 2))
790 # '| %s |' % (name,),
792 # d if d else ' ...',
802 def help_(S, expression, dictionary):
803 '''Accepts a quoted symbol on the top of the stack and prints its docs.'''
804 ((symbol, _), stack) = S
805 word = dictionary[symbol]
806 print(HELP_TEMPLATE % (symbol, getdoc(word), symbol))
807 return stack, expression, dictionary
815 # Several combinators depend on other words in their definitions,
816 # we use symbols to prevent hard-coding these, so in theory, you
817 # could change the word in the dictionary to use different semantics.
818 S_choice = Symbol('choice')
819 S_first = Symbol('first')
820 S_genrec = Symbol('genrec')
821 S_getitem = Symbol('getitem')
823 S_ifte = Symbol('ifte')
824 S_infra = Symbol('infra')
825 S_loop = Symbol('loop')
826 S_pop = Symbol('pop')
827 S_primrec = Symbol('primrec')
828 S_step = Symbol('step')
829 S_swaack = Symbol('swaack')
830 S_times = Symbol('times')
835 def i(stack, expression, dictionary):
837 The i combinator expects a quoted program on the stack and unpacks it
838 onto the pending expression for evaluation.
847 return stack, concat(quote, expression), dictionary
852 def x(stack, expression, dictionary):
858 ... [Q] x = ... [Q] dup i
859 ... [Q] x = ... [Q] [Q] i
860 ... [Q] x = ... [Q] Q
864 return stack, concat(quote, expression), dictionary
869 def b(stack, expression, dictionary):
875 ... [P] [Q] b == ... [P] i [Q] i
876 ... [P] [Q] b == ... P Q
879 q, (p, (stack)) = stack
880 return stack, concat(p, concat(q, expression)), dictionary
885 def dupdip(stack, expression, dictionary):
889 [F] dupdip == dup [F] dip
899 return stack, concat(F, (a, expression)), dictionary
904 def infra(stack, expression, dictionary):
906 Accept a quoted program and a list on the stack and run the program
907 with the list as its stack. Does not affect the rest of the stack.
910 ... [a b c] [Q] . infra
911 -----------------------------
912 c b a . Q [...] swaack
915 (quote, (aggregate, stack)) = stack
916 return aggregate, concat(quote, (stack, (S_swaack, expression))), dictionary
921 def genrec(stack, expression, dictionary):
923 General Recursion Combinator.
926 [if] [then] [rec1] [rec2] genrec
927 ---------------------------------------------------------------------
928 [if] [then] [rec1 [[if] [then] [rec1] [rec2] genrec] rec2] ifte
930 From "Recursion Theory and Joy" (j05cmp.html) by Manfred von Thun:
931 "The genrec combinator takes four program parameters in addition to
932 whatever data parameters it needs. Fourth from the top is an if-part,
933 followed by a then-part. If the if-part yields true, then the then-part
934 is executed and the combinator terminates. The other two parameters are
935 the rec1-part and the rec2-part. If the if-part yields false, the
936 rec1-part is executed. Following that the four program parameters and
937 the combinator are again pushed onto the stack bundled up in a quoted
938 form. Then the rec2-part is executed, where it will find the bundled
939 form. Typically it will then execute the bundled form, either with i or
940 with app2, or some other combinator."
942 The way to design one of these is to fix your base case [then] and the
943 test [if], and then treat rec1 and rec2 as an else-part "sandwiching"
944 a quotation of the whole function.
946 For example, given a (general recursive) function 'F':
949 F == [I] [T] [R1] [R2] genrec
951 If the [I] if-part fails you must derive R1 and R2 from:
956 Just set the stack arguments in front, and figure out what R1 and R2
957 have to do to apply the quoted [F] in the proper way. In effect, the
958 genrec combinator turns into an ifte combinator with a quoted copy of
959 the original definition in the else-part:
962 F == [I] [T] [R1] [R2] genrec
963 == [I] [T] [R1 [F] R2] ifte
965 Primitive recursive functions are those where R2 == i.
968 P == [I] [T] [R] tailrec
969 == [I] [T] [R [P] i] ifte
970 == [I] [T] [R P] ifte
973 (rec2, (rec1, stack)) = stack
974 (then, (if_, _)) = stack
975 F = (if_, (then, (rec1, (rec2, (S_genrec, ())))))
976 else_ = concat(rec1, (F, rec2))
977 return (else_, stack), (S_ifte, expression), dictionary
982 def map_(S, expression, dictionary):
984 Run the quoted program on TOS on the items in the list under it, push a
985 new list with the results in place of the program and original list.
987 # (quote, (aggregate, stack)) = S
988 # results = list_to_stack([
989 # joy((term, stack), quote, dictionary)[0][0]
990 # for term in iter_stack(aggregate)
992 # return (results, stack), expression, dictionary
993 (quote, (aggregate, stack)) = S
995 return (aggregate, stack), expression, dictionary
997 for term in iter_stack(aggregate):
999 batch = (s, (quote, (S_infra, (S_first, batch))))
1000 stack = (batch, ((), stack))
1001 return stack, (S_infra, expression), dictionary
1006 def primrec(stack, expression, dictionary):
1008 From the "Overview of the language JOY":
1010 > The primrec combinator expects two quoted programs in addition to a
1011 data parameter. For an integer data parameter it works like this: If
1012 the data parameter is zero, then the first quotation has to produce
1013 the value to be returned. If the data parameter is positive then the
1014 second has to combine the data parameter with the result of applying
1015 the function to its predecessor.::
1019 > Then primrec tests whether the top element on the stack (initially
1020 the 5) is equal to zero. If it is, it pops it off and executes one of
1021 the quotations, the [1] which leaves 1 on the stack as the result.
1022 Otherwise it pushes a decremented copy of the top element and
1023 recurses. On the way back from the recursion it uses the other
1024 quotation, [*], to multiply what is now a factorial on top of the
1025 stack by the second element on the stack.::
1027 n [Base] [Recur] primrec
1029 0 [Base] [Recur] primrec
1030 ------------------------------
1033 n [Base] [Recur] primrec
1034 ------------------------------------------ n > 0
1035 n (n-1) [Base] [Recur] primrec Recur
1038 recur, (base, (n, stack)) = stack
1040 expression = concat(base, expression)
1042 expression = S_primrec, concat(recur, expression)
1043 stack = recur, (base, (n - 1, (n, stack)))
1044 return stack, expression, dictionary
1047 #def cleave(S, expression, dictionary):
1049 # The cleave combinator expects two quotations, and below that an item X.
1050 # It first executes [P], with X on top, and saves the top result element.
1051 # Then it executes [Q], again with X, and saves the top result.
1052 # Finally it restores the stack to what it was below X and pushes the two
1053 # results P(X) and Q(X).
1055 # (Q, (P, (x, stack))) = S
1056 # p = joy((x, stack), P, dictionary)[0][0]
1057 # q = joy((x, stack), Q, dictionary)[0][0]
1058 # return (q, (p, stack)), expression, dictionary
1063 def branch(stack, expression, dictionary):
1065 Use a Boolean value to select one of two quoted programs to run.
1069 branch == roll< choice i
1073 False [F] [T] branch
1074 --------------------------
1078 -------------------------
1082 (then, (else_, (flag, stack))) = stack
1083 return stack, concat(then if flag else else_, expression), dictionary
1088 ##def ifte(stack, expression, dictionary):
1090 ## If-Then-Else Combinator
1093 ## ... [if] [then] [else] ifte
1094 ## ---------------------------------------------------
1095 ## ... [[else] [then]] [...] [if] infra select i
1100 ## ... [if] [then] [else] ifte
1101 ## -------------------------------------------------------
1102 ## ... [else] [then] [...] [if] infra first choice i
1105 ## Has the effect of grabbing a copy of the stack on which to run the
1106 ## if-part using infra.
1108 ## (else_, (then, (if_, stack))) = stack
1109 ## expression = (S_infra, (S_first, (S_choice, (S_i, expression))))
1110 ## stack = (if_, (stack, (then, (else_, stack))))
1111 ## return stack, expression, dictionary
1116 def cond(stack, expression, dictionary):
1118 This combinator works like a case statement. It expects a single quote
1119 on the stack that must contain zero or more condition quotes and a
1120 default quote. Each condition clause should contain a quoted predicate
1121 followed by the function expression to run if that predicate returns
1122 true. If no predicates return true the default function runs.
1124 It works by rewriting into a chain of nested `ifte` expressions, e.g.::
1126 [[[B0] T0] [[B1] T1] [D]] cond
1127 -----------------------------------------
1128 [B0] [T0] [[B1] [T1] [D] ifte] ifte
1131 conditions, stack = stack
1133 expression = _cond(conditions, expression)
1135 # Attempt to preload the args to first ifte.
1136 (P, (T, (E, expression))) = expression
1138 # If, for any reason, the argument to cond should happen to contain
1139 # only the default clause then this optimization will fail.
1142 stack = (E, (T, (P, stack)))
1143 return stack, expression, dictionary
1146 def _cond(conditions, expression):
1147 (clause, rest) = conditions
1148 if not rest: # clause is [D]
1151 return (P, (T, (_cond(rest, ()), (S_ifte, expression))))
1156 def dip(stack, expression, dictionary):
1158 The dip combinator expects a quoted program on the stack and below it
1159 some item, it hoists the item into the expression and runs the program
1160 on the rest of the stack.
1168 (quote, (x, stack)) = stack
1169 expression = (x, expression)
1170 return stack, concat(quote, expression), dictionary
1175 def dipd(S, expression, dictionary):
1177 Like dip but expects two items.
1181 ---------------------
1185 (quote, (x, (y, stack))) = S
1186 expression = (y, (x, expression))
1187 return stack, concat(quote, expression), dictionary
1192 def dipdd(S, expression, dictionary):
1194 Like dip but expects three items.
1198 -----------------------
1202 (quote, (x, (y, (z, stack)))) = S
1203 expression = (z, (y, (x, expression)))
1204 return stack, concat(quote, expression), dictionary
1209 def app1(S, expression, dictionary):
1211 Given a quoted program on TOS and anything as the second stack item run
1212 the program and replace the two args with the first result of the
1217 -----------------------------------
1218 ... [x ...] [Q] . infra first
1221 (quote, (x, stack)) = S
1222 stack = (quote, ((x, stack), stack))
1223 expression = (S_infra, (S_first, expression))
1224 return stack, expression, dictionary
1229 def app2(S, expression, dictionary):
1230 '''Like app1 with two items.
1234 -----------------------------------
1235 ... [y ...] [Q] . infra first
1236 [x ...] [Q] infra first
1239 (quote, (x, (y, stack))) = S
1240 expression = (S_infra, (S_first,
1241 ((x, stack), (quote, (S_infra, (S_first,
1243 stack = (quote, ((y, stack), stack))
1244 return stack, expression, dictionary
1249 def app3(S, expression, dictionary):
1250 '''Like app1 with three items.
1253 ... z y x [Q] . app3
1254 -----------------------------------
1255 ... [z ...] [Q] . infra first
1256 [y ...] [Q] infra first
1257 [x ...] [Q] infra first
1260 (quote, (x, (y, (z, stack)))) = S
1261 expression = (S_infra, (S_first,
1262 ((y, stack), (quote, (S_infra, (S_first,
1263 ((x, stack), (quote, (S_infra, (S_first,
1264 expression))))))))))
1265 stack = (quote, ((z, stack), stack))
1266 return stack, expression, dictionary
1271 def step(S, expression, dictionary):
1273 Run a quoted program on each item in a sequence.
1277 -----------------------
1282 ------------------------
1286 ... [a b c] [Q] . step
1287 ----------------------------------------
1288 ... a . Q [b c] [Q] step
1290 The step combinator executes the quotation on each member of the list
1291 on top of the stack.
1293 (quote, (aggregate, stack)) = S
1295 return stack, expression, dictionary
1296 head, tail = aggregate
1297 stack = quote, (head, stack)
1299 expression = tail, (quote, (S_step, expression))
1300 expression = S_i, expression
1301 return stack, expression, dictionary
1306 def times(stack, expression, dictionary):
1308 times == [-- dip] cons [swap] infra [0 >] swap while pop
1312 --------------------- w/ n <= 0
1317 -----------------------
1322 ------------------------------------- w/ n > 1
1323 ... . Q (n - 1) [Q] times
1326 # times == [-- dip] cons [swap] infra [0 >] swap while pop
1327 (quote, (n, stack)) = stack
1329 return stack, expression, dictionary
1332 expression = n, (quote, (S_times, expression))
1333 expression = concat(quote, expression)
1334 return stack, expression, dictionary
1337 # The current definition above works like this:
1340 # --------------------------------------
1341 # [P] nullary [Q [P] nullary] loop
1343 # while == [pop i not] [popop] [dudipd] tailrec
1345 #def while_(S, expression, dictionary):
1346 # '''[if] [body] while'''
1347 # (body, (if_, stack)) = S
1348 # while joy(stack, if_, dictionary)[0][0]:
1349 # stack = joy(stack, body, dictionary)[0]
1350 # return stack, expression, dictionary
1355 def loop(stack, expression, dictionary):
1357 Basic loop combinator.
1361 -----------------------
1365 ------------------------
1369 quote, (flag, stack) = stack
1371 expression = concat(quote, (quote, (S_loop, expression)))
1372 return stack, expression, dictionary
1377 def cmp_(stack, expression, dictionary):
1379 cmp takes two values and three quoted programs on the stack and runs
1380 one of the three depending on the results of comparing the two values:
1384 ------------------------- a > b
1388 ------------------------- a = b
1392 ------------------------- a < b
1395 L, (E, (G, (b, (a, stack)))) = stack
1396 expression = concat(G if a > b else L if a < b else E, expression)
1397 return stack, expression, dictionary
1400 # FunctionWrapper(cleave),
1401 # FunctionWrapper(while_),
1406 #divmod_ = pm = __(n2, n1), __(n4, n3)
1408 BinaryBuiltinWrapper(operator.eq),
1409 BinaryBuiltinWrapper(operator.ge),
1410 BinaryBuiltinWrapper(operator.gt),
1411 BinaryBuiltinWrapper(operator.le),
1412 BinaryBuiltinWrapper(operator.lt),
1413 BinaryBuiltinWrapper(operator.ne),
1415 BinaryBuiltinWrapper(operator.xor),
1416 BinaryBuiltinWrapper(operator.lshift),
1417 BinaryBuiltinWrapper(operator.rshift),
1419 BinaryBuiltinWrapper(operator.and_),
1420 BinaryBuiltinWrapper(operator.or_),
1422 BinaryBuiltinWrapper(operator.add),
1423 BinaryBuiltinWrapper(operator.floordiv),
1424 BinaryBuiltinWrapper(operator.mod),
1425 BinaryBuiltinWrapper(operator.mul),
1426 BinaryBuiltinWrapper(operator.pow),
1427 BinaryBuiltinWrapper(operator.sub),
1428 BinaryBuiltinWrapper(operator.truediv),
1430 UnaryBuiltinWrapper(bool),
1431 UnaryBuiltinWrapper(operator.not_),
1433 UnaryBuiltinWrapper(abs),
1434 UnaryBuiltinWrapper(operator.neg),
1435 UnaryBuiltinWrapper(sqrt),
1437 UnaryBuiltinWrapper(floor),
1438 UnaryBuiltinWrapper(round),
1441 del F # Otherwise Sphinx autodoc will pick it up.
1444 for name, primitive in getmembers(genlib, isfunction):
1445 inscribe(SimpleFunctionWrapper(primitive))
1448 add_aliases(_dictionary, ALIASES)
1451 DefinitionWrapper.add_definitions(definitions, _dictionary)