Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;; Lisp code to work with ranges of integers
- ;; (range 2 7) --> (2 3 4 5 6 7)
- ;; [3 5] --> (3 4 5)
- ;; (iota 4) --> (1 2 3 4)
- ;; (ι 3) --> (1 2 3)
- ;; (sum [1 4]) --> 10
- ;; Inspired by the comp.lang.lisp discussions:
- ;; 1) "My opinion re LISP"
- ;; 2) "APL-like operators defined in Lisp?"
- ; (range i f) produces the range of integers from i(nitial) to f(inal)
- (defun range (i f &optional (a nil))
- (if (eq i f)
- (cons i a)
- (range i (1- f) (cons f a))))
- ; read the bracketed expression [i f] as (range i f)
- (set-macro-character #\] (get-macro-character #\)))
- (set-macro-character #\[
- #'(lambda (stream char)
- (let ((pair (read-delimited-list #\] stream t)))
- (list 'quote (range (car pair) (cadr pair))))))
- ; (sum list) produces the sum of the numbers in the given list
- (defun sum (l) (apply #'+ l))
- ; emulate APL's iota operator ι and []IO index origin variable
- (defvar *IO* 1) ; index origin
- (defun iota (f) (range *IO* f))
- ; shortcut for the above
- (defun ι (f) (iota f))
- ; examples of the above
- (sum [2 7]) ; produces 27
- (sum [1 100]) ; produces 5050
- (sum (iota 10)) ; produces 55
- (sum (ι 4)) ; produces 10
Advertisement
Add Comment
Please, Sign In to add comment