Content deleted Content added
m change link markup |
Nowikify code example containing square brackets |
||
Line 19:
That probably requires some explanation. In joy, everything is a function that takes a [[Stack (computing)|stack]] as an argument and returns a stack as a result. For instance, the number 5 is not, as it might appear to be, an integer constant, but instead a short program that pushes the number 5 onto the stack. The + operator pops two numbers off the stack and pushes their sum. The dup operator simply duplicates the top element of the stack by pushing a copy of it. So this definition of the square function says to make a copy of the top element and then multiply the two top elements, leaving the square of the original top element on top of the stack. There is no need for a formal parameter at all. This design makes joy one of the most powerful and concise languages, as illustrated by this definition of [[quicksort]]:
<pre>
<nowiki>
DEFINE qsort ==
[small]
Line 25 ⟶ 27:
[[swap] dip cons concat]
binrec .
</nowiki>
</pre>
"binrec" is one of joy's many [[recursion|recursive]] [[combinator|combinators]], implementing binary recursion. It expects four quoted programs on top of the stack which represent the termination condition (if a list is "small" (1 or 0 elements) it is already sorted), what to do if the termination condition is met (in this case nothing), what to do by default (split the list into two halves by comparing each element with the pivot), and finally what to do at the end (insert the pivot between the two sorted halves).
|