You probably want to create a list, like this:
(define (med x y z) (car(cdr(list x y z)))
However, it seems like a waste to bundle up the values into a list just to undo them again. This would have the same effect:
(define (med x y z) y)
You probably want to create a list, like this:
(define (med x y z) (car(cdr(list x y z)))
However, it seems like a waste to bundle up the values into a list just to undo them again. This would have the same effect:
(define (med x y z) y)
Note that as defined, (med . rest)
is equivalent to (cadr rest)
(except that med
only 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 using sort
, length
and list-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:
(if (and (
(<x y)
(<y z)
y
if
(and (
(<y x)
(<x z)
x
z
) ) ) ) )
The format for if
is:
(if test-expr true-expr false-expr)
All of your terms are sub-terms of the conditional, and there's no true-expr
or false-expr
. You'd want to write your code as:
(if (and ...)
y
(if (...) ; we know that (not (and (< x y) (< y z))
x
z))
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 of if
s:
(cond (test result)
(test result)
(test result)
... )
For your code, it would be:
(cond ((and ...) y)
((...) x)
(else z))
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)
, not foo(1, 2 ,3)
), unlike mathematical notation where parentheses surround just the arguments.
while outis did a pretty good job of explaining the issue, there's one other important bit you need to know
(<x y)
calls the function named <x with the parameter y. you need to make sure you add a space inbetween the < and the x, like so:
(< x y)