APL-like extensions to Scheme

Arithmetic Operators

Operator Description Example(s)
(+ x y) Addition (+ '(1 2 3 4) '(4 3 2 1)) is (5 5 5 5) and (+ #t #t) is 2.
(- x y) Subtraction (- '((1 2) (3 4)) 1) is ((0 1) (2 3)).
(* x y) Multiplication (* 2 3) is 6 and (* #f '(1 2 3)) is (0 0 0).
(/ x y) Division (/ '(1 2 3) 2) is (1/2 1 3/2)
(% x y) Modulus (% '(1 2 3) 2) is (1 0 1).
(^ x y) Exponentiation (^ '((1 2) (3 4)) '((1 2) (3 4))) is ((1 4) (27 256)).

Logical Operators

Operator Description Example(s)
(*. x y) And (*. #t '(#t #t #f)) is (#t #t #f).
(+. x y) Or (+. #t '(#t #t #f)) is (#t #t #t)
(~ x) Not (~ #t) is #f.

Comparison Operators

Operator Description Example(s)
(= x y) Equal (= 2 '(1 2 3 4)) is (#f #t #f #f).
(< x y) Less than (< '((1 2) (3 4)) 4) is ((#t #t) (#t #f)).
(> x y) Greater than (> '((1 2) (3 4)) 4) is ((#f #f) (#f #t)).
(<= x y) Less than or equal (<= 7 8) is #t.
(>= x y) Greater than or equal (>= '((9 1) (3 9)) '((1 2) (3 4))) is '((#t #f) (#t #t)).
(<> x y) Not equal (<> '(1 2 3) '(4 2 1)) is (#t #f #t).

Higher Order Operators

Operator Description Example(s)
((: f g) u v) Generalized inner product ((: + *) u v) is the inner product of u and v.
((@ f) u v) Generalized outer product ((@ *) (i 12) (i 12)) returns a 12x12 times-table.
((@ f g) A B) Generalized matrix product ((@ + *) A B) is the matrix product of A and B.
((^ f n) x) Iterate f n-times, i.e., f(f(f(...))). ((^ sqrt 2) x) is the 4th root of x.
((_ f) u) Reduce u with f. ((_ *) (i 7)) is 7! and ((_ +) (i 7)) is 28.
((r m n) u) Reshape u to have dimensions m and n (Rho). ((r 2 2) (i 4)) is ((1 2) (3 4)).
((r) A) Matrix dimensions ((r) '((1 2) (3 4))) is (2 2).

Misc. Operators

Operator Description Example(s)
(i n) Sequence of integers 1 to n (Iota). (i 5) is (1 2 3 4 5).
(p u) Permutations of elements of u. (p '(a b c)) is ((a b c) (a c b) ... (c b a)).
(t A) Matrix transpose (t '((1 2) (3 4))) is ((1 3)(2 4)).
($ u v) Select from v using u. ($ '(#t #f #t #f) '(1 2 3 4)) is (1 3).
(alt u) Alternate signs in u. (alt (i 4)) is (1 -2 3 -4).
(! n) Factorial of n. (! 4) is 24 and (! (i 4)) is (1 2 6 24).
(? n) Random number between 1 and n. (? 10) is a random number between 1 and 10.

Compute prime numbers.

(define primes
  (lambda (n)
    ($ (= 2 ((_ +) (= 0 ((@ %) (i n) (i n))))) 
       (i n))))

e = 2.718281828...

(define e
  ((_ +) (/ (! (- (i 100) 1)))))

Sort a list.

(define sort
  (lambda (ls)
    ($ ((_ <) (p ls)) (p ls))))

Find an eigenvector.

(define norm
  (lambda (v)
    (^ ((_ +) ((_ +) (^ v 2))) 1/2)))

(define eigenvector
  (lambda (A)
    (let ((d (length A)))
      ((^ (lambda (x) ((@ + *) A (/ x (norm x)))) 100)
       ((r d 1) (i d))))))

Get baby APL here.

Get full-blown APL here.