Lecture 2 Functions
- Questions
- 1.2.6 Could you go over the expression tree for the print statement?
- Expressions
- describes a computation and evaluates
- similar to asking your computer a question
- Example
- 1 + 2 + 3 -5
- Call expressions
- min, max, etc.
- everything can be expressed with call expressions
- Anatomy of Call expression
- add (2, 3)
- add - operator
- 2, 3 - operand
- Evaluation procedure for call expressions
- Evaluate the operator and then the operand subexpressions
- Apply the function that is the value of the operator to the arguments that re the values of the operands
- Sub expression, expression inside another expression
- Names, Assignment, and User-Defined Functions
- Using def statement to define own functions
- Function allows area to be updated with the new radius value
- Types of Expressions
- Primitive expressions: 2, add, ‘hello’
- Call expressions: max(2,3)
- g, h = min, max
- g = min
- h = max
- Environment Diagrams
- visualize the interpreter’s process
- Code (left):
- Statements and expressions
- Arrows indicate evaluation order
- Frames (right):
- Each name is bound to a value
- Within a frame, a name cannot be repeated
- Assignment Statements
- Execution rules
- Evaluate all expression to the right of = from left to right
- Bind all names to the left of = to those resulting values in the current frame
- Defining Functions
- Assignment is a basic means of abstraction: binds names to values
- Function definition: binds names to expressions
- def statement
- Function signature indicates how many arguments a function takes
- The function body defines the computation performed when the function is applied
- Execution procedure for def statements
- Create a function with signature
- Set the body of that function indented after the first line
- Bind to that function in the current frame
- Don’t necessarily need to memorize all of the procedures, but be familiar with it (included on final exam sheet)
- Return values
- returns a value to whoever calls the functions
- code that runs after it is not run
- Calling User-Defined Functions
- Procedure
- Add a local frame, forming a new environment
- Bind the function’s formal parameters to its arguments in that frame
- Execute the body of the function in that new environment
- Environment diagram
- return value not binding
- Name of frame = name of function
- Looking up names in Environments
- Every expression is evaluated in the context of an environment
- An Environment is a sequence of frames
- A name evaluates to the value bound to that name in the earliest frame of the current environment in which that name is found
- start with current environment, start our way back, until we find it
- search local frame first, then global frame
- Can only have one copy of a name in a frame
- Summary
- An expression is asking your computer a question
2.