Wodan58 / Joy

Manfred von Thun's Programming Language Joy
http://wodan58.github.io
Other
83 stars 9 forks source link

Built-in - while #5

Open PapillonAll opened 3 weeks ago

PapillonAll commented 3 weeks ago

In the pdf documentation JOP.pdf 'while' is described as:

[while ...]... -> [B jump-on-false-to-(1) D [B] [D] while (1) ...]... While executing B yields true executes D.

and in the manual at https://wodan58.github.io/plain-manual.html, it is described as:

while : [B] [D] -> ... While executing B yields true executes D.

So, although the 'while' example in the pdf documentation:

10 [] [pop] [[dup [pred] dip] dip cons] while popd [1 2 3 4 5 6 7 8 9 10] equal.

returns true, I am really confused about what [pop] does, because when running joy with -d flag, it appears to do nothing!

Please, I'd like some explanation about how 'while' works.

Wodan58 commented 2 weeks ago

The [pop] inspects the second item on the stack and treats it as a boolean. Here is a quote from Manfred:

From time to time I have thought about an implementation of\ Joy using such an array, but abandoned the idea because of all\ sorts of difficulties. Your language might overcome those.\ \ I'd like to hear more about these.

OK, here it is. In Joy, consider\ [if-part] [then-part] [else-part] ifte\ or anything like that in which the three parts are on the top\ of the stack and now the ifte combinator gets to work. Joy does

  1. Remove the three parts from the top of the stack.
  2. Save as much of the remainder of the stack as needed for 5.
  3. Execute the if-part (and note that typically this will use up parts of the stack to get a truth value).
  4. Note whether top of stack is true or false.
  5. Restore stack to what it was in step 3.
  6. If the saved top of stack was true/false, execute the if-part/then-part.

In a linked list implementation step 2 is easy: just save the whole\ stack, as a link. In step 5, forget about the stack that was mangled\ in step 3, just restore the link from step 2.\ Pretty much the same thing happens in recursion combinators such\ as linrec, binrec, tailrec, while, nestrec and so on. Also the\ aggregate combinators map, filter and fold need something very\ similar, although they do not have an explicit if-part. Finally,\ the innocent looking nullary, unary and binary combinators also\ have to save and later restore the stack. It is all very easy\ with a linked list implementation of the stack.\ \ Another case: the operators stack and unstack and the infra combinator\ are easiest with linked implementations for the stack and the lists\ (quotations).