user1816790
user1816790

Reputation:

Using conditionals in Scheme

I have to create the following: A Scheme procedure named 'proc2' which takes 4 numbers as arguments and returns the value of the largest argument minus the smallest.

So I want to write (define proc2 lambda(a b c d) ... )

Is there any way I can evaluate (> a b), (> a c), (> a d) at the same time? I want to get the largest (and the smallest)number without having to write nested ifs.

Upvotes: 3

Views: 1049

Answers (2)

itsbruce
itsbruce

Reputation: 4843

If you want to find the smallest and largest members of the list and you are not allowed to use the standard min and max library functions, then I can think of three approaches

  1. Write your own min and max functions (hint: recursion). Apply both to the list to find your two values. Perform the subtraction.
  2. Write a combined function (again, recursive) which will pass through the list once, returning another two-member list which contains the max and min. If the first element in the returned list is the max, then (apply - (find-min-and-max 3 2 8 7)), where find-min-and-max is your function, would return the result of the subtraction.
  3. Use map.

Option 1 is less efficient than option 2 but much simpler to write. Option 3 is more complex than either but actually does what you asked (that is, compare a to b, c and d "at the same time").

For example, if I defined the following function:

(define (compare test x l)
  (map (lambda (y) (test x y)) l))

then

(compare < 3 '(1 2 4))

would return (#f #f #t)

How is this useful to you? Well, if (compare < x l) returns all true, then x is smaller than all elements of l. If it returns all false, then x is bigger than all elements of l. So you could use map to build the code you want, but I think it would be ugly and not the most efficient way to do it. It does do what you specifically asked for, though (multiple simultaneous comparisons of list elements).

Upvotes: 0

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 236112

Can you use the max and min procedures? if the answer is yes, it's pretty simple:

(- (max a b c d) (min a b c d))

If not, remember that <, >, <=, >= accept a variable number of arguments, so this is valid code and will tell you if a is smaller than b and b is smaller than c and c is smaller than d (although you'll have to test more combinations of b, c, d to make sure that a is the smallest value).

(< a b c d)

Also remember to consider the cases when two or more numbers are equal (that's why it's a good idea to use <= instead of <).

Anyway, you'll have to use conditionals. Maybe nested ifs, or perhaps a cond to make things simpler - you can work out the details yourself, I'm guessing this is homework.

Upvotes: 0

Related Questions