Quote:
Originally Posted by Raptors06
I'm in agreement - that does look simple and intuitive. Will have to look into that.
|
And the best part is it can become really powerful fairly quickly. Lets go back to the sum function. Now in mathematics there is Sigma which serves to sum things:
It will take only a little work to get our sum function to work with this very general and useful tool. Below is a function that is a little more general than even mathematical definition of sigma. Sigma takes as its arguments
a function to apply to an input, a stopping condition, a way to get to the next sum value, and the starting data m. One of the really cool things in Scheme is that a function can be passed exactly like any other variable.
Code:
(define (sigma function next condition m)
(if (condition m)
0
(+ (function m)
(sigma function condition next (next m)))))
Now to get the sum for our average function we just plug in arguments to sigma:
(sigma car cdr null? b)
Now how about a sum of squares from 1 to 49? like 1^2 +2^2 + 3^2 + 4^2 ...
all you need is:
Code:
(sigma square add1 lessthan50 1)
(define (add1 x) (+ x 1))
(define (lessthan50 y) (> 50 y))
Super simple!