Search code examples
schemeracketquotesicp

Pair? function applying on Quote in Racket


In order to implement derivative of given polynomial, I need to factorize the polynomial, i.e., (* 3 x y) should be the product of 3 and (* x y).

So I implemented a function multiplicand to get the second factor of a product:

(define (multiplicand p) 
  (let ((second-factor (cdr (cdr p))))
  (if (pair? second-factor) (cons '* second-factor)
   second-factor)))

and the test code is

(multiplicand '(* x y))

But the output is '(* y). It seems that the condition (pair? second-factor) equals #true with second-factor values 'y.

Can anybody help me with this, thanks a lot.


Solution

  • Bear in mind that (cdr (cdr ...)) is returning a list (not an element!), so pair? will return true if the list has enough elements (three or more). Perhaps you were aiming for something like this?

    (define (multiplicand p) 
      (if (null? (cdddr p)) ; assuming list has at least 3 elements
          p
          `(* ,(second p) (* ,(third p) ,(fourth p)))))
    
    (multiplicand '(* x y))
     => (* x y)
    
    (multiplicand '(* 3 x y))
     => (* 3 (* x y))