简体   繁体   English

对? 功能应用于球拍中的报价

[英]Pair? function applying on Quote in Racket

In order to implement derivative of given polynomial, I need to factorize the polynomial, ie, (* 3 xy) should be the product of 3 and (* xy) . 为了实现给定多项式的导数,我需要分解多项式,即(* 3 xy)应该是3(* xy)的乘积。

So I implemented a function multiplicand to get the second factor of a product: 因此,我实现了一个multiplicand函数以获得multiplicand的第二个因子:

(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) . 但是输出是'(* y) It seems that the condition (pair? second-factor) equals #true with second-factor values 'y . 看来条件(pair? second-factor)等于#truesecond-factor'y

Can anybody help me with this, thanks a lot. 有人可以帮我吗,非常感谢。

Bear in mind that (cdr (cdr ...)) is returning a list (not an element!), so pair? 请记住, (cdr (cdr ...))返回一个列表(不是元素!),所以pair? will return true if the list has enough elements (three or more). 如果列表具有足够的元素(三个或更多),则将返回true。 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))

Manipulating symbolic expressions is what match is made for: match符号表达式是为了实现以下目的:

(define (multiplicand p)
  (match p
     [(list '* m n) n]
     [_ (error 'multiplicand (~a "expected product, got: " p))]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM