Pergunta

We are tasked to print out the values in the pascal triangle in this manner

(pascal 2)
(1 2 1)
(pascal 0)
(1)

I copied the code for the binomial thereom somewhere in the internet defined as follows:

(defun choose(n k)
        (labels ((prod-enum (s e)
            (do ((i s (1+ i)) (r 1 (* i r))) ((> i e) r)))
          (fact (n) (prod-enum 1 n)))
         (/ (prod-enum (- (1+ n) k) n) (fact k))))

Now I'm trying to create a list out of the values here in my pascal function:

(defun pascal (start end) 
  (do ((i start (+ i 1)))
       ((> i end) )
       (print (choose end i) ))
)

The function produces 1 2 1 NIL if I test it with (pascal 0 2). How can I eliminate the NIL and create the list?

Foi útil?

Solução

Note: I explicitly didn't provide an implementation of pascal, since the introductory “we are tasked…” suggests that this is a homework assignment.

Instead of printing the result of (choose end i) on each iteration, just collect the values produced by (choose end i) into a list of results, and then return the results at the end of the loop. It's a common idiom to construct a list in reverse order by pushing elements into it, and then using nreverse to reverse it to produce the final return value. For instance, you might implement range by:

(defun range (start end &optional (delta 1) &aux (results '()))
  (do ((i start (+ i delta)))
      ((>= i end) (nreverse results))
    (push i results)))

or (It always feels satisfying to write a do/do* loop that doesn't need any code in the body.)

(defun range (start end &optional (delta 1))
  (do* ((results '() (list* i results))
        (i start (+ i delta)))
       ((>= i end) (nreverse results))))

so that

(range 0 10 3)
;=> (0 3 6 9)

However, since the rows in Pascal's triangle are palidromes, you don't need to reverse them. Actually, since the rows are palindromes, you should even be able to adjust the loop to generate just half the list return, e.g.,

(revappend results results)

when there are an even number of elements, and

(revappend results (rest results))

when there are an odd number.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top