3
votes

Define a function sum, which takes two numbers, or two real functions, and returns their sum. E.g.

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

I get that for the sum of two numbers the code would be the following:

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

But what would be the code for the two real functions...? How would I do this? can anyone please help?

Also how would I do this:

Define a function sum-all which works like sum, but works on a list of numbers or a list of functions. Assume the list contains at least one element. E.g.

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

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

Note: this is not homework... I was going through a past midterm.

5
the function that I tried with is posted above: (define sum(lambda (x y) (+ x y))) - user1028
for ((sum cos exp) 0) to work sum would need to be (lambda (f g) (lambda (v) (+ (f v) (g v)))) to combine this with the other sum function (lambda (a b) (+ a b)) you'd need to look at the types of the arguments and decide what to do with them. - Dan D.
(define sum (lambda (x y) (+ x y))) is nearly equivalent to (define sum +). - Christoffer Hammarström

5 Answers

3
votes

For the first part of your question, I'll have to agree with PJ.Hades that this is the simplest solution:

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

For the second part, we can make good use of higher-order procedures for writing a simple solution that is a generalization of the previous one:

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

In both procedures, I'm assuming that all the operands are of the same kind: they're either all-numbers or all-functions, as inferred from the sample code provided in the question.

1
votes

Do you mean this?

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

       (cond 

         [(empty? lst) 0]

         [else (foldr + 0 lst)]))
1
votes
((lambda (a b) (+ a b)) 4 5)

this how it is done using lambda.

using define we can write as follows

(define (sum a b) (+ a b))
0
votes

I'm a little rusty with my Scheme, so perhaps there's a better way to do this, but you could do:

(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)))))