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

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

99 LISP problems: Problem #17

Solution to the 99 LISP Problems #17

I solved #18 first and am using the solution to that to do this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
(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))))

Lisp dialect: Steel Bank Common Lisp

99 LISP problems: Problem #18

Solution to the 99 LISP Problems #18

Very similar to the solution for #16 eariler.

1
2
3
4
5
6
7
8
9
(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)))

Lisp dialect: Steel Bank Common Lisp

99 LISP problems: Problem #16

Solution to the 99 LISP Problems #16

This seemingly innocuous problem turned out to be a little challenging too. Like I have mentioned earlier, I strongly prefer a pure functional or recursive solution. Therefore, carrying the state around (in this case, the position of the current in the list) is slightly tough. I knew I should be using closures. I have used some sort of let + lambda. Not sure if this is elegant.

1
2
3
4
5
6
7
8
(defun drop (alist n)
  (let ((i 1))
    (mapcan
      (lambda (x)
        (let ((j i))
          (setf i (1+ i))
          (if (= (mod j n) 0) nil (list x))))
      alist)))

Lisp dialect: Steel Bank Common Lisp