Question

(defun help(a x)
  (if (null x) nil
    (cons (cons a (car x)) (help a (cdr x)))))

(defun partition(x)
    (if (null x) '(nil)
    (append (help (car x) (partition(cdr x))) (partition(cdr x)))))

This works like this: (partition '(a b)) -> ((A B) (A) (B) NIL) I'm trying to understand how it works. Can someone illustrate what's going on to get the result? I tried following the code and writing down on paper but i failed.

Was it helpful?

Solution

The trace function allows you to visualize function calls in the LISP REPL.

Example output from sbcl

* (defun help(a x)
  (if (null x) nil
    (cons (cons a (car x)) (help a (cdr x)))))

HELP
* (defun partition(x)
  (if (null x) '(nil)
    (append (help (car x) (partition(cdr x))) (partition(cdr x)))))

PARTITION
* (trace help)

(HELP)
* (trace partition)

(PARTITION)
* (partition '(a b))
  0: (PARTITION (A B))
    1: (PARTITION (B))
      2: (PARTITION NIL)
      2: PARTITION returned (NIL)
      2: (HELP B (NIL))
        3: (HELP B NIL)
        3: HELP returned NIL
      2: HELP returned ((B))
      2: (PARTITION NIL)
      2: PARTITION returned (NIL)
    1: PARTITION returned ((B) NIL)
    1: (HELP A ((B) NIL))
      2: (HELP A (NIL))
        3: (HELP A NIL)
        3: HELP returned NIL
      2: HELP returned ((A))
    1: HELP returned ((A B) (A))
    1: (PARTITION (B))
      2: (PARTITION NIL)
      2: PARTITION returned (NIL)
      2: (HELP B (NIL))
        3: (HELP B NIL)
        3: HELP returned NIL
      2: HELP returned ((B))
      2: (PARTITION NIL)
      2: PARTITION returned (NIL)
    1: PARTITION returned ((B) NIL)
  0: PARTITION returned ((A B) (A) (B) NIL)
((A B) (A) (B) NIL)

Out side of that I'm not entirely sure how to be of more help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top