asb: head /dev/brain > /dev/www

My home, musings, and wanderings on the world wide web.

99 LISP problems: Problem #23

Solution to the 99 LISP Problems #23

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
(defun element-at (alist n)
  (if (< (length alist) n)
    nil
    (if (= n 1)
      (car alist)
      (element-at (cdr alist) (1- n)))))

(defun remove-at (alist n)
  (let ((i 1))
    (mapcan
      (lambda (x)
        (let ((j i))
          (setf i (1+ i))
          (if (= j n) nil (list x))))
      alist)))

(defun rnd-select (alist n)
  (if (<= n 0)
    nil
    (let ((k (1+ (random (length alist)))))
      (append
        (list (element-at alist k))
        (rnd-select (remove-at alist k) (1- n))))))

Lisp dialect: Steel Bank Common Lisp

99 LISP problems: Problem #22

Solution to the 99 LISP Problems #22

1
2
3
4
5
6
7
8
9
10
11
(defun range-inner (lo hi)
  (if (> lo hi)
    nil
    (append
      (list lo)
      (range-inner (1+ lo) hi))))

(defun range (left right)
  (if (< right left)
    (reverse (range-inner right left))
    (range-inner left right)))

Lisp dialect: Steel Bank Common Lisp

99 LISP problems: Problem #19

Solution to the 99 LISP Problems #19

Uses the two previous solutions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
(defun slice (alist from to)
  (let ((i 1))
    (mapcan
      (lambda (x)
        (let ((j i))
          (setf i (1+ i))
          (if (and (>= j from) (<= j to))
            (list x) nil)))
      alist)))

(defun split (alist n)
  (list
    (slice alist 1 n)
    (slice alist (1+ n) (length alist))))

(defun rotate (alist n)
  (let* ((m (if (>= n 0) n (+ (length alist) n)))
         (pieces (split alist m)))
    (append (cadr pieces) (car pieces))))

Lisp dialect: Steel Bank Common Lisp