09-18-2013

posted Sep 18, 2013, 11:47 AM by Samuel Konstantinovich   [ updated Sep 18, 2013, 9:11 PM ]
Variables, Functions, and Pi.

Variables are constructs in computer science that have values that are known. We use them to store values to keep track of them later. 
In mathematics, we say  Let x be 5. This is how you can think of a variable in computer science. Keep in mind the value can be changed at any time.

(define a 3)  
(define b 4)
(define c (+ a b) )     a and b evaluate toe 3 and 4, then the addition is performed. The number 7 is stored in c.

the format is:
(define variableName Expression)

After you define c in terms of a and b, realize that if a or b change later, c is not going to change, as the value 7 was stored. The expression a+b was not stored.

Functions are like mathematical functions f(x) g(x,y) etc. Functions accept 0 or more parameters and evaluate to a single value. A function to square a value, would require one parameter, that is the value you want to square. It would then return the result:

(define (sq x) (* x x ))   

the format is:
(define (functionName parameter1 parameter2...) (expression that uses parameters)  )
-Note: variables are defined in a similar manner to functions you must notice the extra parenthesis around the function name compared to the lack of parenthesis for the variable name

A function can be used to apply a formula to any number of parameters. The parameters are the values you put into a function f(x)  can receive one parameter x, so f(2) is an example of a single parameter function. 

(define (foo a b) (+ (* 2 a) b) )     
In mathematical terms this definition is saying that foo(a,b) is  2a+b

(foo 5 4) is saying substitute 5 and 4 into the expression (+ (* 2 a) b)
(+ (* 2 5) 4)  which is 14


Comments