I’m just playing around with scheme/lisp and was thinking about how I would right my own definition of average. I’m not sure how to do some things that I think are required though.
- define a procedure that takes an arbitrary number of arguments
- count those arguments
- pass the argument list to (+) to sum them together
Does someone have an example of defining average? I don’t seem to know enough about LISP to form a web search that gets back the results I’m looking for.
The definition would be a very simple one-liner, but without spoiling it, you should look into:
a “rest” argument — this
(define (foo . xs) ...xs...)definesfooas a function that takes any number of arguments and they’re available as a list which will be the value ofxs.lengthreturns the length of a list.applytakes a function and a list of values and applies the function to these values.When you get that, you can go for more:
see the
foldlfunction to avoid applying a list on a potentially very big list (this can matter in some implementations where the length of the argument list is limited, but it wouldn’t make much difference in Racket).note that Racket has exact rationals, and you can use
exact->inexactto make a more efficient floating-point version.And the spoilers are:
(define (average . ns) (/ (apply + ns) (length ns)))Make it require one argument:
(define (average n . ns) (/ (apply + n ns) (add1 (length ns))))Use
foldl:(define (average n . ns) (/ (foldl + 0 (cons n ns)) (add1 (length ns))))Make it use floating point:
(define (average n . ns) (/ (foldl + 0.0 (cons n ns)) (add1 (length ns))))