Jump to content

Joy (programming language)

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by 68.35.245.175 (talk) at 10:03, 1 June 2004 (created page). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Joy

Joy is a simple functional language which is almost unique (besides perhaps unlambda) in its lack of a lambda operator, and therefore lack of formal parameters. To illustrate this with a common example, here's how the square function might be defined in an imperative language (C):

int square(int x) {
  return x*x;
}

The variable x is a formal parameter which is replaced by the actual value to be squared when the function is called. Now here's how the same function would be defined in a functional language (scheme):

(define square
  (lambda (x)
    (* x x)))

This is different in many ways, but it still uses the formal parameter x in the same way. Now here's how the square function would be defined in joy:

DEFINE square == dup * .

That probably requires some explanation. In joy, everything is a function that takes a 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:

DEFINE qsort ==
  [small]
  []
  [uncons [>] split]
  [[swap] dip cons concat]
  binrec .

"binrec" is one of joy's many recursive 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).