recursion - How do recursive functions work in Lisp? -


so i'm coding in lisp , came function counts number of atoms in list (with no sub-lists). code this:

(defun num-atoms (list)   (cond     ((null list) 0)     ((atom list) 1)     (t (+ (num-atoms (car list))           (num-atoms (cdr list)))))) 

and works , makes sense me. if call function list (1 2 3) in argument should go follows:

  • (num-atoms '(1 2 3))
  • not null
  • not atom
  • num-atoms(1)
  • atom returns 1
  • num-atoms ((2 3))
  • not null
  • not atom
  • num-atoms (2)
  • return 1
  • ....
  • and on

but, if write code this:

(defun num-atoms (list)   (cond     ((null list) 0)     ((atom list) 1)     (t (+ (num-atoms (cdr list))           (num-atoms (car list)))))) 

here switched de car , cdr positions in last line.

it still works ! , if trace, gives me number of atoms in same order ! counts 1 first in '(1 2 3) list , on. can explain me how 2nd version of code still works ? dont understand logic here.

if trace both functions you'll see how hey differ.

in first version, atoms processed in order because function processes first element (car) , remaining elements (cdr).

in second version, atoms processes in reverse order because function first processes remaining elements before processing first element. first atom found last in list, , stack unwinds.

but of course result same in both cases since addition commutative.

* (defun num-atoms(list)   (cond    ((null list) 0)    ((atom list) 1)    (t (+ (num-atoms (car list)) (num-atoms (cdr list))))))  num-atoms * (trace num-atoms)  (num-atoms) * (num-atoms '(1 2 3))   0: (num-atoms (1 2 3))     1: (num-atoms 1)     1: num-atoms returned 1     1: (num-atoms (2 3))       2: (num-atoms 2)       2: num-atoms returned 1       2: (num-atoms (3))         3: (num-atoms 3)         3: num-atoms returned 1         3: (num-atoms nil)         3: num-atoms returned 0       2: num-atoms returned 1     1: num-atoms returned 2   0: num-atoms returned 3 3 

and

* (defun num-atoms(list)   (cond    ((null list) 0)    ((atom list) 1)    (t (+ (num-atoms (cdr list)) (num-atoms (car list))))))  num-atoms * (num-atoms '(1 2 3))   0: (num-atoms (1 2 3))     1: (num-atoms (2 3))       2: (num-atoms (3))         3: (num-atoms nil)         3: num-atoms returned 0         3: (num-atoms 3)         3: num-atoms returned 1       2: num-atoms returned 1       2: (num-atoms 2)       2: num-atoms returned 1     1: num-atoms returned 2     1: (num-atoms 1)     1: num-atoms returned 1   0: num-atoms returned 3 3 * 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -