Scheme编程和函数重载

时间:2012-03-04 08:43:19

标签: sum scheme overloading

定义一个函数sum,它接受​​两个数字或两个实数函数,并返回它们的。 E.g。

(sum 1 2) => 3
((sum cos exp) 0) => 2

我得到的是两个数字的总和,代码如下:

(define sum (lambda (x y)
  (+ x y)))

但是这两个实际功能的代码是什么?我该怎么做?有人可以帮忙吗?

另外我该怎么做:

  

定义一个函数sum-all,其作用类似sum,但适用于数字的列表或函数的列表。假设列表包含至少一个元素。    E.g。

(sum-all (list 1 2 3)) => 6

((sum-all (list cos sin exp)) 0) => 2

注意:这不是作业......我正在经历一个过去的期中考试。

5 个答案:

答案 0 :(得分:3)

对于你问题的第一部分,我必须同意PJ.Hades这是最简单的解决方案:

(define (sum x y)
  (if (and (number? x) (number? y))
      (+ x y)
      (lambda (n)
        (+ (x n) (y n)))))

对于第二部分,我们可以很好地利用高阶程序来编写一个简单的解决方案,这是前一个解决方案的概括:

(define (sum-all lst)
  (if (andmap number? lst)
      (apply + lst)
      (lambda (n)
        (apply + (map (lambda (f) (f n)) lst)))))

在这两个过程中,我假设所有操作数都是相同类型的:它们是全数字或全部函数,如问题中提供的示例代码所推断。

答案 1 :(得分:1)

你是说这个吗?

(define (sum a b)
    (if (and (number? a) (number? b))
        (+ a b)
        (lambda (x)
            (+ (a x) (b x)))))

答案 2 :(得分:1)

(define (sum lst)

       (cond 

         [(empty? lst) 0]

         [else (foldr + 0 lst)]))

答案 3 :(得分:1)

((lambda (a b) (+ a b)) 4 5)

这是如何使用lambda完成的。

使用define我们可以写如下

(define (sum a b) (+ a b))

答案 4 :(得分:0)

我的计划有点生疏,所以也许有更好的方法可以做到这一点,但你可以做到:

(define (sum-all lst)
  (define (sum-funcs-helper funcs x)
    (if (empty? funcs)
        0
        (+ ((car funcs) x)
           (sum-funcs-helper (cdr funcs) x))))
  (if (empty? lst)
      0 ;; Beats me what this is supposed to return.
      (if (number? (car lst))
          (apply + lst)
          (lambda (x) (sum-funcs-helper lst x)))))