aher

Lisp code to work with ranges of integers

Mar 18th, 2013
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lisp 1.18 KB | None | 0 0
  1. ;; Lisp code to work with ranges of integers
  2. ;; (range 2 7) --> (2 3 4 5 6 7)
  3. ;; [3 5]       --> (3 4 5)
  4. ;; (iota 4)    --> (1 2 3 4)
  5. ;; (ι 3)       --> (1 2 3)
  6. ;; (sum [1 4]) --> 10
  7. ;; Inspired by the comp.lang.lisp discussions:
  8. ;;   1) "My opinion re LISP"
  9. ;;   2) "APL-like operators defined in Lisp?"
  10.  
  11. ; (range i f) produces the range of integers from i(nitial) to f(inal)
  12. (defun range (i f &optional (a nil))
  13.   (if (eq i f)
  14.     (cons i a)
  15.     (range i (1- f) (cons f a))))
  16.  
  17. ; read the bracketed expression [i f] as (range i f)
  18. (set-macro-character #\] (get-macro-character #\)))
  19.  
  20. (set-macro-character #\[
  21.   #'(lambda (stream char)
  22.     (let ((pair (read-delimited-list #\] stream t)))
  23.       (list 'quote (range (car pair) (cadr pair))))))
  24.  
  25. ; (sum list) produces the sum of the numbers in the given list
  26. (defun sum (l) (apply #'+ l))
  27.  
  28. ; emulate APL's iota operator ι and []IO index origin variable
  29. (defvar *IO* 1) ; index origin
  30.  
  31. (defun iota (f) (range *IO* f))
  32.  
  33. ; shortcut for the above
  34. (defun ι (f) (iota f))
  35.  
  36. ; examples of the above
  37. (sum [2 7])     ; produces 27
  38.  
  39. (sum [1 100])   ; produces 5050
  40.  
  41. (sum (iota 10)) ; produces 55
  42.  
  43. (sum (ι 4))     ; produces 10
Advertisement
Add Comment
Please, Sign In to add comment