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 builtins import map, object, range, zip
28 from inspect import getdoc
29 from functools import wraps
30 from itertools import count
31 from inspect import getmembers, isfunction
34 from .parser import text_to_expression, Symbol
35 from .utils import generated_library as genlib
36 from .utils.stack import (
55 # This is the main dict we're building.
59 def inscribe(function):
60 '''A decorator to inscribe functions into the default dictionary.'''
61 _dictionary[function.name] = function
66 '''Return a dictionary of Joy functions for use with joy().'''
67 return _dictionary.copy()
75 ('floordiv', ['/floor', '//']),
77 ('truediv', ['/', 'div']),
78 ('mod', ['%', 'rem', 'remainder', 'modulus']),
81 ('getitem', ['pick', 'at']),
92 ('rolldown', ['roll<']),
93 ('rollup', ['roll>']),
99 def add_aliases(D, A):
101 Given a dict and a iterable of (name, [alias, ...]) pairs, create
102 additional entries in the dict mapping each alias to the named function
103 if it's in the dict. Aliases for functions not in the dict are ignored.
105 for name, aliases in A:
110 for alias in aliases:
116 *fraction [uncons] dip uncons [swap] dip concat [*] infra [*] dip cons
117 *fraction0 concat [[swap] dip * [*] dip] infra
118 anamorphism [pop []] swap [dip swons] genrec
119 average [sum 1.0 *] [size] cleave /
120 binary nullary [popop] dip
121 cleave fork [popd] dip
122 codireco cons dip rest cons
123 dinfrirst dip infra first
124 unstack ? [uncons ?] loop pop
125 down_to_zero [0 >] [dup --] while
127 enstacken stack [clear] dip
128 flatten [] swap [concat] step
130 gcd 1 [tuck modulus dup 0 >] loop pop
131 ifte [nullary not] dipd branch
133 least_fraction dup [gcd] infra [div] concat map
134 make_generator [codireco] ccons
135 nullary [stack] dinfrirst
139 product 1 swap [*] step
141 range [0 <=] [1 - dup] anamorphism
142 range_to_zero unit [down_to_zero] infra
144 size 0 swap [pop ++] step
146 step_zero 0 roll> step
149 ternary unary [popop] dip
152 while swap [nullary] cons dup dipd concat loop
156 # ifte == [nullary] dipd swap branch
157 # genrec == [[genrec] cons cons cons cons] nullary swons concat ifte
159 # Another definition for while. FWIW
160 # while == over [[i] dip nullary] ccons [nullary] dip loop
164 ##second == rest first
165 ##third == rest rest first
169 ##z-down == [] swap uncons swap
170 ##z-up == swons swap shunt
171 ##z-right == [swons] cons dip uncons swap
172 ##z-left == swons [uncons swap] dip swap
175 ##divisor == popop 2 *
177 ##radical == swap dup * rollup * 4 * - sqrt
180 ##q0 == [[divisor] [minusb] [radical]] pam
181 ##q1 == [[root1] [root2]] pam
182 ##quadratic == [q0] ternary i [q1] ternary
186 ##PE1.1 == + dup [+] dip
187 ##PE1.2 == dup [3 & PE1.1] dip 2 >>
188 ##PE1.3 == 14811 swap [PE1.2] times pop
189 ##PE1 == 0 0 66 [7 PE1.3] times 4 PE1.3 pop
191 #PE1.2 == [PE1.1] step
192 #PE1 == 0 0 66 [[3 2 1 3 1 2 3] PE1.2] times [3 2 1 3] PE1.2 pop
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):
222 (a, (b, stack)) = stack
224 return (result, stack), expression, dictionary
228 def UnaryBuiltinWrapper(f):
230 Wrap functions that take one argument and return a single result.
234 def inner(stack, expression, dictionary):
237 return (result, stack), expression, dictionary
241 class DefinitionWrapper(object):
243 Provide implementation of defined functions, and some helper methods.
246 def __init__(self, name, body_text, doc=None):
247 self.name = self.__name__ = name
248 self.body = text_to_expression(body_text)
249 self._body = tuple(iter_stack(self.body))
250 self.__doc__ = doc or body_text
251 self._compiled = None
253 def __call__(self, stack, expression, dictionary):
255 return self._compiled(stack, expression, dictionary) # pylint: disable=E1102
256 expression = list_to_stack(self._body, expression)
257 return stack, expression, dictionary
260 def parse_definition(class_, defi):
262 Given some text describing a Joy function definition parse it and
263 return a DefinitionWrapper.
265 return class_(*(n.strip() for n in defi.split(None, 1)))
268 def add_definitions(class_, defs, dictionary):
270 Scan multi-line string defs for definitions and add them to the
273 for definition in _text_to_defs(defs):
274 class_.add_def(definition, dictionary)
277 def add_def(class_, definition, dictionary, fail_fails=False):
279 Add the definition to the dictionary.
281 F = class_.parse_definition(definition)
282 dictionary[F.name] = F
285 def load_definitions(class_, filename, dictionary):
286 with open(filename) as f:
287 lines = [line for line in f if '==' in line]
289 class_.add_def(line, dictionary)
292 def _text_to_defs(text):
295 for line in text.splitlines()
296 if not line.startswith('#')
307 def inscribe_(stack, expression, dictionary):
309 Create a new Joy function definition in the Joy dictionary. A
310 definition is given as a string with a name followed by a double
311 equal sign then one or more Joy functions, the body. for example:
315 If you want the definition to persist over restarts, enter it into
316 the definitions.txt resource.
318 definition, stack = stack
319 DefinitionWrapper.add_def(definition, dictionary, fail_fails=True)
320 return stack, expression, dictionary
324 @SimpleFunctionWrapper
326 '''Parse the string on the stack to a Joy expression.'''
328 expression = text_to_expression(text)
329 return expression, stack
333 # @SimpleFunctionWrapper
335 # '''Attempt to infer the stack effect of a Joy expression.'''
337 # effects = infer_expression(E)
338 # e = list_to_stack([(fi, (fo, ())) for fi, fo in effects])
343 @SimpleFunctionWrapper
348 getitem == drop first
350 Expects an integer and a quote on the stack and returns the item at the
351 nth position in the quote counting from 0.
355 -------------------------
359 n, (Q, stack) = stack
360 return pick(Q, n), stack
364 @SimpleFunctionWrapper
371 Expects an integer and a quote on the stack and returns the quote with
372 n items removed off the top.
376 ----------------------
380 n, (Q, stack) = stack
391 @SimpleFunctionWrapper
394 Expects an integer and a quote on the stack and returns the quote with
395 just the top n items in reverse order (because that's easier and you can
396 use reverse if needed.)
400 ----------------------
404 n, (Q, stack) = stack
417 @SimpleFunctionWrapper
420 Use a Boolean value to select one of two items.
424 ----------------------
429 ---------------------
432 Currently Python semantics are used to evaluate the "truthiness" of the
433 Boolean value (so empty string, zero, etc. are counted as false, etc.)
435 (if_, (then, (else_, stack))) = stack
436 return then if if_ else else_, stack
440 @SimpleFunctionWrapper
443 Use a Boolean value to select one of two items from a sequence.
447 ------------------------
452 -----------------------
455 The sequence can contain more than two items but not fewer.
456 Currently Python semantics are used to evaluate the "truthiness" of the
457 Boolean value (so empty string, zero, etc. are counted as false, etc.)
459 (flag, (choices, stack)) = stack
460 (else_, (then, _)) = choices
461 return then if flag else else_, stack
465 @SimpleFunctionWrapper
467 '''Given a list find the maximum.'''
469 return max(iter_stack(tos)), stack
473 @SimpleFunctionWrapper
475 '''Given a list find the minimum.'''
477 return min(iter_stack(tos)), stack
481 @SimpleFunctionWrapper
483 '''Given a quoted sequence of numbers return the sum.
485 sum == 0 swap [+] step
488 return sum(iter_stack(tos)), stack
492 @SimpleFunctionWrapper
495 Expects an item on the stack and a quote under it and removes that item
496 from the the quote. The item is only removed once.
500 ------------------------
504 (tos, (second, stack)) = S
505 l = list(iter_stack(second))
507 return list_to_stack(l), stack
511 @SimpleFunctionWrapper
513 '''Given a list remove duplicate items.'''
515 I = list(iter_stack(tos))
516 return list_to_stack(sorted(set(I), key=I.index)), stack
520 @SimpleFunctionWrapper
522 '''Given a list return it sorted.'''
524 return list_to_stack(sorted(iter_stack(tos))), stack
528 @SimpleFunctionWrapper
530 '''Clear everything from the stack.
533 clear == stack [pop stack] loop
543 @SimpleFunctionWrapper
544 def disenstacken(stack):
546 The disenstacken operator expects a list on top of the stack and makes that
547 the stack discarding the rest of the stack.
553 @SimpleFunctionWrapper
555 '''Reverse the list on the top of the stack.
558 reverse == [] swap shunt
562 for term in iter_stack(tos):
568 @SimpleFunctionWrapper
570 '''Concatinate the two lists on the top of the stack.
573 [a b c] [d e f] concat
574 ----------------------------
578 (tos, (second, stack)) = S
579 return concat(second, tos), stack
583 @SimpleFunctionWrapper
585 '''Like concat but reverses the top list into the second.
588 shunt == [swons] step == reverse swap concat
590 [a b c] [d e f] shunt
591 ---------------------------
595 (tos, (second, stack)) = stack
598 second = term, second
603 @SimpleFunctionWrapper
606 Replace the two lists on the top of the stack with a list of the pairs
607 from each list. The smallest list sets the length of the result list.
609 (tos, (second, stack)) = S
612 for a, b in zip(iter_stack(tos), iter_stack(second))
614 return list_to_stack(accumulator), stack
618 @SimpleFunctionWrapper
622 return tos + 1, stack
626 @SimpleFunctionWrapper
630 return tos - 1, stack
634 @SimpleFunctionWrapper
645 a, (b, stack) = stack
651 return int(math.floor(n))
653 floor.__doc__ = math.floor.__doc__
657 @SimpleFunctionWrapper
660 divmod(x, y) -> (quotient, remainder)
662 Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
671 Return the square root of the number a.
672 Negative numbers return complex roots.
677 assert a < 0, repr(a)
678 r = math.sqrt(-a) * 1j
684 # if isinstance(text, str):
685 # return run(text, stack)
690 @SimpleFunctionWrapper
692 '''The identity function.'''
697 @SimpleFunctionWrapper
699 '''True if the form on TOS is void otherwise False.'''
701 return _void(form), stack
705 return any(not _void(i) for i in iter_stack(form))
716 def words(stack, expression, dictionary):
717 '''Print all the words in alphabetical order.'''
718 print(' '.join(sorted(dictionary)))
719 return stack, expression, dictionary
724 def sharing(stack, expression, dictionary):
725 '''Print redistribution information.'''
726 print("You may convey verbatim copies of the Program's source code as"
727 ' you receive it, in any medium, provided that you conspicuously'
728 ' and appropriately publish on each copy an appropriate copyright'
729 ' notice; keep intact all notices stating that this License and'
730 ' any non-permissive terms added in accord with section 7 apply'
731 ' to the code; keep intact all notices of the absence of any'
732 ' warranty; and give all recipients a copy of this License along'
734 ' You should have received a copy of the GNU General Public License'
735 ' along with Thun. If not see <http://www.gnu.org/licenses/>.')
736 return stack, expression, dictionary
741 def warranty(stack, expression, dictionary):
742 '''Print warranty information.'''
743 print('THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY'
744 ' APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE'
745 ' COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM'
746 ' "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR'
747 ' IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES'
748 ' OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE'
749 ' ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS'
750 ' WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE'
751 ' COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.')
752 return stack, expression, dictionary
755 # def simple_manual(stack):
757 # Print words and help for each word.
759 # for name, f in sorted(FUNCTIONS.items()):
761 # boxline = '+%s+' % ('-' * (len(name) + 2))
764 # '| %s |' % (name,),
766 # d if d else ' ...',
776 def help_(S, expression, dictionary):
777 '''Accepts a quoted symbol on the top of the stack and prints its docs.'''
778 ((symbol, _), stack) = S
779 word = dictionary[symbol]
780 print(HELP_TEMPLATE % (symbol, getdoc(word), symbol))
781 return stack, expression, dictionary
789 # Several combinators depend on other words in their definitions,
790 # we use symbols to prevent hard-coding these, so in theory, you
791 # could change the word in the dictionary to use different semantics.
792 S_choice = Symbol('choice')
793 S_first = Symbol('first')
794 S_genrec = Symbol('genrec')
795 S_getitem = Symbol('getitem')
797 S_ifte = Symbol('ifte')
798 S_infra = Symbol('infra')
799 S_loop = Symbol('loop')
800 S_pop = Symbol('pop')
801 S_primrec = Symbol('primrec')
802 S_step = Symbol('step')
803 S_swaack = Symbol('swaack')
804 S_times = Symbol('times')
809 def i(stack, expression, dictionary):
811 The i combinator expects a quoted program on the stack and unpacks it
812 onto the pending expression for evaluation.
821 return stack, concat(quote, expression), dictionary
826 def x(stack, expression, dictionary):
832 ... [Q] x = ... [Q] dup i
833 ... [Q] x = ... [Q] [Q] i
834 ... [Q] x = ... [Q] Q
838 return stack, concat(quote, expression), dictionary
843 def b(stack, expression, dictionary):
849 ... [P] [Q] b == ... [P] i [Q] i
850 ... [P] [Q] b == ... P Q
853 q, (p, (stack)) = stack
854 return stack, concat(p, concat(q, expression)), dictionary
859 def dupdip(stack, expression, dictionary):
863 [F] dupdip == dup [F] dip
873 return stack, concat(F, (a, expression)), dictionary
878 def infra(stack, expression, dictionary):
880 Accept a quoted program and a list on the stack and run the program
881 with the list as its stack. Does not affect the rest of the stack.
884 ... [a b c] [Q] . infra
885 -----------------------------
886 c b a . Q [...] swaack
889 (quote, (aggregate, stack)) = stack
890 return aggregate, concat(quote, (stack, (S_swaack, expression))), dictionary
895 def genrec(stack, expression, dictionary):
897 General Recursion Combinator.
900 [if] [then] [rec1] [rec2] genrec
901 ---------------------------------------------------------------------
902 [if] [then] [rec1 [[if] [then] [rec1] [rec2] genrec] rec2] ifte
904 From "Recursion Theory and Joy" (j05cmp.html) by Manfred von Thun:
905 "The genrec combinator takes four program parameters in addition to
906 whatever data parameters it needs. Fourth from the top is an if-part,
907 followed by a then-part. If the if-part yields true, then the then-part
908 is executed and the combinator terminates. The other two parameters are
909 the rec1-part and the rec2-part. If the if-part yields false, the
910 rec1-part is executed. Following that the four program parameters and
911 the combinator are again pushed onto the stack bundled up in a quoted
912 form. Then the rec2-part is executed, where it will find the bundled
913 form. Typically it will then execute the bundled form, either with i or
914 with app2, or some other combinator."
916 The way to design one of these is to fix your base case [then] and the
917 test [if], and then treat rec1 and rec2 as an else-part "sandwiching"
918 a quotation of the whole function.
920 For example, given a (general recursive) function 'F':
923 F == [I] [T] [R1] [R2] genrec
925 If the [I] if-part fails you must derive R1 and R2 from:
930 Just set the stack arguments in front, and figure out what R1 and R2
931 have to do to apply the quoted [F] in the proper way. In effect, the
932 genrec combinator turns into an ifte combinator with a quoted copy of
933 the original definition in the else-part:
936 F == [I] [T] [R1] [R2] genrec
937 == [I] [T] [R1 [F] R2] ifte
939 Primitive recursive functions are those where R2 == i.
942 P == [I] [T] [R] tailrec
943 == [I] [T] [R [P] i] ifte
944 == [I] [T] [R P] ifte
947 (rec2, (rec1, stack)) = stack
948 (then, (if_, _)) = stack
949 F = (if_, (then, (rec1, (rec2, (S_genrec, ())))))
950 else_ = concat(rec1, (F, rec2))
951 return (else_, stack), (S_ifte, expression), dictionary
956 def map_(S, expression, dictionary):
958 Run the quoted program on TOS on the items in the list under it, push a
959 new list with the results in place of the program and original list.
961 # (quote, (aggregate, stack)) = S
962 # results = list_to_stack([
963 # joy((term, stack), quote, dictionary)[0][0]
964 # for term in iter_stack(aggregate)
966 # return (results, stack), expression, dictionary
967 (quote, (aggregate, stack)) = S
969 return (aggregate, stack), expression, dictionary
971 for term in iter_stack(aggregate):
973 batch = (s, (quote, (S_infra, (S_first, batch))))
974 stack = (batch, ((), stack))
975 return stack, (S_infra, expression), dictionary
980 def primrec(stack, expression, dictionary):
982 From the "Overview of the language JOY":
984 > The primrec combinator expects two quoted programs in addition to a
985 data parameter. For an integer data parameter it works like this: If
986 the data parameter is zero, then the first quotation has to produce
987 the value to be returned. If the data parameter is positive then the
988 second has to combine the data parameter with the result of applying
989 the function to its predecessor.
993 > Then primrec tests whether the top element on the stack (initially
994 the 5) is equal to zero. If it is, it pops it off and executes one of
995 the quotations, the [1] which leaves 1 on the stack as the result.
996 Otherwise it pushes a decremented copy of the top element and
997 recurses. On the way back from the recursion it uses the other
998 quotation, [*], to multiply what is now a factorial on top of the
999 stack by the second element on the stack.
1001 n [Base] [Recur] primrec
1003 0 [Base] [Recur] primrec
1004 ------------------------------
1007 n [Base] [Recur] primrec
1008 ------------------------------------------ n > 0
1009 n (n-1) [Base] [Recur] primrec Recur
1012 recur, (base, (n, stack)) = stack
1014 expression = concat(base, expression)
1016 expression = S_primrec, concat(recur, expression)
1017 stack = recur, (base, (n - 1, (n, stack)))
1018 return stack, expression, dictionary
1021 #def cleave(S, expression, dictionary):
1023 # The cleave combinator expects two quotations, and below that an item X.
1024 # It first executes [P], with X on top, and saves the top result element.
1025 # Then it executes [Q], again with X, and saves the top result.
1026 # Finally it restores the stack to what it was below X and pushes the two
1027 # results P(X) and Q(X).
1029 # (Q, (P, (x, stack))) = S
1030 # p = joy((x, stack), P, dictionary)[0][0]
1031 # q = joy((x, stack), Q, dictionary)[0][0]
1032 # return (q, (p, stack)), expression, dictionary
1037 def branch(stack, expression, dictionary):
1039 Use a Boolean value to select one of two quoted programs to run.
1043 branch == roll< choice i
1047 False [F] [T] branch
1048 --------------------------
1052 -------------------------
1056 (then, (else_, (flag, stack))) = stack
1057 return stack, concat(then if flag else else_, expression), dictionary
1062 ##def ifte(stack, expression, dictionary):
1064 ## If-Then-Else Combinator
1067 ## ... [if] [then] [else] ifte
1068 ## ---------------------------------------------------
1069 ## ... [[else] [then]] [...] [if] infra select i
1074 ## ... [if] [then] [else] ifte
1075 ## -------------------------------------------------------
1076 ## ... [else] [then] [...] [if] infra first choice i
1079 ## Has the effect of grabbing a copy of the stack on which to run the
1080 ## if-part using infra.
1082 ## (else_, (then, (if_, stack))) = stack
1083 ## expression = (S_infra, (S_first, (S_choice, (S_i, expression))))
1084 ## stack = (if_, (stack, (then, (else_, stack))))
1085 ## return stack, expression, dictionary
1090 def cond(stack, expression, dictionary):
1092 This combinator works like a case statement. It expects a single quote
1093 on the stack that must contain zero or more condition quotes and a
1094 default quote. Each condition clause should contain a quoted predicate
1095 followed by the function expression to run if that predicate returns
1096 true. If no predicates return true the default function runs.
1098 It works by rewriting into a chain of nested `ifte` expressions, e.g.::
1100 [[[B0] T0] [[B1] T1] [D]] cond
1101 -----------------------------------------
1102 [B0] [T0] [[B1] [T1] [D] ifte] ifte
1105 conditions, stack = stack
1107 expression = _cond(conditions, expression)
1109 # Attempt to preload the args to first ifte.
1110 (P, (T, (E, expression))) = expression
1112 # If, for any reason, the argument to cond should happen to contain
1113 # only the default clause then this optimization will fail.
1116 stack = (E, (T, (P, stack)))
1117 return stack, expression, dictionary
1120 def _cond(conditions, expression):
1121 (clause, rest) = conditions
1122 if not rest: # clause is [D]
1125 return (P, (T, (_cond(rest, ()), (S_ifte, expression))))
1130 def dip(stack, expression, dictionary):
1132 The dip combinator expects a quoted program on the stack and below it
1133 some item, it hoists the item into the expression and runs the program
1134 on the rest of the stack.
1142 (quote, (x, stack)) = stack
1143 expression = (x, expression)
1144 return stack, concat(quote, expression), dictionary
1149 def dipd(S, expression, dictionary):
1151 Like dip but expects two items.
1155 ---------------------
1159 (quote, (x, (y, stack))) = S
1160 expression = (y, (x, expression))
1161 return stack, concat(quote, expression), dictionary
1166 def dipdd(S, expression, dictionary):
1168 Like dip but expects three items.
1172 -----------------------
1176 (quote, (x, (y, (z, stack)))) = S
1177 expression = (z, (y, (x, expression)))
1178 return stack, concat(quote, expression), dictionary
1183 def app1(S, expression, dictionary):
1185 Given a quoted program on TOS and anything as the second stack item run
1186 the program and replace the two args with the first result of the
1191 -----------------------------------
1192 ... [x ...] [Q] . infra first
1194 (quote, (x, stack)) = S
1195 stack = (quote, ((x, stack), stack))
1196 expression = (S_infra, (S_first, expression))
1197 return stack, expression, dictionary
1202 def app2(S, expression, dictionary):
1203 '''Like app1 with two items.
1207 -----------------------------------
1208 ... [y ...] [Q] . infra first
1209 [x ...] [Q] infra first
1212 (quote, (x, (y, stack))) = S
1213 expression = (S_infra, (S_first,
1214 ((x, stack), (quote, (S_infra, (S_first,
1216 stack = (quote, ((y, stack), stack))
1217 return stack, expression, dictionary
1222 def app3(S, expression, dictionary):
1223 '''Like app1 with three items.
1226 ... z y x [Q] . app3
1227 -----------------------------------
1228 ... [z ...] [Q] . infra first
1229 [y ...] [Q] infra first
1230 [x ...] [Q] infra first
1233 (quote, (x, (y, (z, stack)))) = S
1234 expression = (S_infra, (S_first,
1235 ((y, stack), (quote, (S_infra, (S_first,
1236 ((x, stack), (quote, (S_infra, (S_first,
1237 expression))))))))))
1238 stack = (quote, ((z, stack), stack))
1239 return stack, expression, dictionary
1244 def step(S, expression, dictionary):
1246 Run a quoted program on each item in a sequence.
1250 -----------------------
1255 ------------------------
1259 ... [a b c] [Q] . step
1260 ----------------------------------------
1261 ... a . Q [b c] [Q] step
1263 The step combinator executes the quotation on each member of the list
1264 on top of the stack.
1266 (quote, (aggregate, stack)) = S
1268 return stack, expression, dictionary
1269 head, tail = aggregate
1270 stack = quote, (head, stack)
1272 expression = tail, (quote, (S_step, expression))
1273 expression = S_i, expression
1274 return stack, expression, dictionary
1279 def times(stack, expression, dictionary):
1281 times == [-- dip] cons [swap] infra [0 >] swap while pop
1285 --------------------- w/ n <= 0
1290 ---------------------------------
1295 --------------------------------- w/ n > 1
1296 ... . Q (n - 1) [Q] times
1299 # times == [-- dip] cons [swap] infra [0 >] swap while pop
1300 (quote, (n, stack)) = stack
1302 return stack, expression, dictionary
1305 expression = n, (quote, (S_times, expression))
1306 expression = concat(quote, expression)
1307 return stack, expression, dictionary
1310 # The current definition above works like this:
1313 # --------------------------------------
1314 # [P] nullary [Q [P] nullary] loop
1316 # while == [pop i not] [popop] [dudipd] tailrec
1318 #def while_(S, expression, dictionary):
1319 # '''[if] [body] while'''
1320 # (body, (if_, stack)) = S
1321 # while joy(stack, if_, dictionary)[0][0]:
1322 # stack = joy(stack, body, dictionary)[0]
1323 # return stack, expression, dictionary
1328 def loop(stack, expression, dictionary):
1330 Basic loop combinator.
1334 -----------------------
1338 ------------------------
1342 quote, (flag, stack) = stack
1344 expression = concat(quote, (quote, (S_loop, expression)))
1345 return stack, expression, dictionary
1350 def cmp_(stack, expression, dictionary):
1352 cmp takes two values and three quoted programs on the stack and runs
1353 one of the three depending on the results of comparing the two values:
1357 ------------------------- a > b
1361 ------------------------- a = b
1365 ------------------------- a < b
1368 L, (E, (G, (b, (a, stack)))) = stack
1369 expression = concat(G if a > b else L if a < b else E, expression)
1370 return stack, expression, dictionary
1373 # FunctionWrapper(cleave),
1374 # FunctionWrapper(while_),
1379 #divmod_ = pm = __(n2, n1), __(n4, n3)
1381 BinaryBuiltinWrapper(operator.eq),
1382 BinaryBuiltinWrapper(operator.ge),
1383 BinaryBuiltinWrapper(operator.gt),
1384 BinaryBuiltinWrapper(operator.le),
1385 BinaryBuiltinWrapper(operator.lt),
1386 BinaryBuiltinWrapper(operator.ne),
1388 BinaryBuiltinWrapper(operator.xor),
1389 BinaryBuiltinWrapper(operator.lshift),
1390 BinaryBuiltinWrapper(operator.rshift),
1392 BinaryBuiltinWrapper(operator.and_),
1393 BinaryBuiltinWrapper(operator.or_),
1395 BinaryBuiltinWrapper(operator.add),
1396 BinaryBuiltinWrapper(operator.floordiv),
1397 BinaryBuiltinWrapper(operator.mod),
1398 BinaryBuiltinWrapper(operator.mul),
1399 BinaryBuiltinWrapper(operator.pow),
1400 BinaryBuiltinWrapper(operator.sub),
1401 BinaryBuiltinWrapper(operator.truediv),
1403 UnaryBuiltinWrapper(bool),
1404 UnaryBuiltinWrapper(operator.not_),
1406 UnaryBuiltinWrapper(abs),
1407 UnaryBuiltinWrapper(operator.neg),
1408 UnaryBuiltinWrapper(sqrt),
1410 UnaryBuiltinWrapper(floor),
1413 del F # Otherwise Sphinx autodoc will pick it up.
1416 for name, primitive in getmembers(genlib, isfunction):
1417 inscribe(SimpleFunctionWrapper(primitive))
1420 add_aliases(_dictionary, ALIASES)
1423 DefinitionWrapper.add_definitions(definitions, _dictionary)