The problem this time is to get the median of three values (easy)
I did this:
(define (med x y z) (car(cdr(x y z)))
and it was accepted but when testing it:
(med 3 4 5)
I get this error:
Error: attempt to call a non-procedure
(2 3 4)
And when entering letters instead of number i get:
(md x y z)
Error: undefined varia
y
(package user)
Using something besides x y z I get:
(md d l m)
Error: undefined variable
d
(package user)
the question was deleted dont know how anyway
write a function that return the median of 3 values
Sorry for editing the question I got that I should put the values in order first not just a sill car and cdr thing so I did so
33> (define (med x y z)
(if(and(
(<x y) (<y z) y
if(and(
(<y x) (<x z) x z)))))
Warning: invalid expression
(if (and< (<x y) (<y z) y if (and ((<y x) (<x z) x z))))
but as u see Im getting a warning so what is wronge ?
Note that as defined,
(med . rest)is equivalent to(cadr rest)(except thatmedonly takes three values). Personally, I would expect a function that’s supposed to return the median of values to return, well, the median, regardless of list order. For example,(med 4 2 5)would return 4 and(3 0 9 6 5)would return 5.As for the syntax error (which doesn’t matter so much for writing
med, since there is a better way usingsort,lengthandlist-ref), you don’t have your parentheses in the right spots. Here’s another way of writing what you have now, lining up terms with their siblings and to the right of their ancestors:The format for
ifis:All of your terms are sub-terms of the conditional, and there’s no
true-exprorfalse-expr. You’d want to write your code as:Note that you might be ably to simplfy the later tests, since you know the earlier tests are false.
You could also use a
cond, which is clearer than a nested sequence ofifs:For your code, it would be:
There’s nothing too special about
else(it’s a syntactical construct rather than an expression, not that it matters much). You can use any value that evaluates to true (e.g.#t) instead.Remember, parentheses surround both the function and arguments in Lisp (
(foo 1 2 3), notfoo(1, 2 ,3)), unlike mathematical notation where parentheses surround just the arguments.