【问题标题】:Scheme Adding Terms from lists方案从列表中添加术语
【发布时间】:2015-03-15 02:29:42
【问题描述】:

我正在编写一个用于对多项式执行运算的方案程序。我目前正在研究一种结合所有类似术语的方法。例如,如果我有多项式:1x^2 + 2x^2 + 4x^3,则该函数应结合类似项 1x^2 和 2x^2 并输出最终多项式 3x^2 + 4x^3。它使用递归。

我首先对多项式进行排序。然后,如果长度为零,则什么也不做。我调用了另一个函数来检查指数是否相等,如果相等,则添加这两个项,然后遍历列表。

我遇到的问题是:

当我检查两个项是否相等时,我将它们加在一起。完成此操作后,我无法弄清楚如何将其添加到原始列表中并在进行递归调用时将该列表传递给该列表。我知道我应该使用“cons”添加到列表的前面。我知道我应该使用 cdr(cdr list) 来跳过我已经添加的两个术语。

如何在函数中创建一个新列表以添加到原始列表中?这是我到目前为止所做的。其中一些不起作用。 (正在尝试不同的东西)我坚持的部分是当我创建“a”和“b”并打印它们时。我不想打印它们,而是想将它们放在一个列表中,以便我可以将其与原始列表一起使用。到目前为止,我尝试了中间带有“缺点”的注释部分(分号表示注释)。这就是我的列表的定义方式。第一项是系数,第二项是指数。示例:(2 3) Coeff = 2, expon = 3

    (define p1 '((2 3)(3 2)(5 2)))

    (define (simplify p)
    (sort p GT)
    (cond [(= (length p) 0) (print 0)]
    [(= (length p) 1) (printpoly p)]
    [
     (if(EQExp? (car p) (cadr p))
     (let([a (+ (coeff (car p)) (coeff (cadr p)))])
     (let([b (expon (cadr p))])
     (print a)
     (display "x^")
     (print b)
       (printpoly(car([list '((a b))])))
     ; (printpoly y)
     ; (cons (cons ('(a) '(expon (cdr p)))) p)
     ; (cons  y p)
     ;(print (expon (car p)))
     (set! p (cdr p))
     (simplify p)
         )
       ;)
     )
     (if(> (length p) 1)
      ((printTerm (car p))
      (display " + ")
      (set! p (cdr p))
      (simplify p))
      ((=(length p) 1)
       (set! p (cdr p))
       (simplify p)
      )
      )
     )
     ]
     [else
     (set! p (cdr p))
     (simplify p)
     ]
     )
     )

【问题讨论】:

    标签: scheme


    【解决方案1】:

    多项式运算可能很复杂,因此将任务分解为许多小运算非常重要。特别是,您需要有一个单独的函数来打印多项式。下面您将看到简化如何用相同的指数替换这两项。缺少的是打印多项式的函数。

    (define the-zero-polynomial '())
    
    (define (exponent t) ; t stands for term
      (second t))
    
    (define (coef t) ; t 
      (first t))
    
    (define (same-degree? t1 t2)
      (or (equal? t1 t2)
          (and (not (null? t1)) (not (null? t2))
               (= (exponent t1) (exponent t2)))))
    
    (define p1 '((2 3) (3 2) (5 2)))
    
    (define (simplify p) ; p is unsorted
      (simplify-sorted (sort p GT)))
    
    (define (simplify-sorted p)
      (cond 
        [(= (length p) 0) the-zero-polynomial]
        [(= (length p) 1) p]
        [else
         ; now p = (list t1 t2 t ...)
         (let ([t1 (first p)] [t2 (second p)])
           (cond
             [(same-degree? t1 t2)
              ; same degree, replace (list t1 t2 t ...) 
              ; with                 (list t1+t2 t ...)
               (let ([t1+t2 (list (+ (coef t1) (coef t2))
                                  (exponent t1))])
                 (simplify-sorted (cons t1+t2 (cddr p))))]
             [else
              (cons t1 (simplify (cdr p)))]))]))
    

    【讨论】:

    • 非常感谢。计划很难学习。我在这个方法上花了 6 个多小时。但现在一切都说得通了。我已经有了打印方法。我只需要做一些小改动并添加一些东西来使打印工作。我一定会记得将方法分解为更小的方法。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-16
    • 2014-10-01
    • 2016-10-21
    • 1970-01-01
    • 2013-03-13
    相关资源
    最近更新 更多