Thursday, April 4, 2013

Elements of Programming

Every programming language has three things:
  1. Primitives
  2. Expressions to combine primitives
  3. Ways to abstract expressions, introducing a name for the expression
Scala has an interactive shell that one can use to test simple expressions called a REPL (Read, Evaluate,  Print, Loop). You evaluate an expression by taking the leftmost operator, evaluating its operands, and applying the operator on the operands.

You can define a function in Scala as follows: def square(x:Double):Double = x * x. The second Double could be omitted. 

There are two ways of evaluating a function application. The first is called Call-By-Value.
  1. Evaluate function arguments from left to right
  2. Replace function application by function's RHS, and
  3. Replace the formal parameters in the function by the actual arguments
The Call-By-Name method of evaluating a function is similar but it doesn't evaluate the arguments until the very end. This is beneficial because it will not evaluate arguments that are not used. However, there may be repeated evaluations of the same expressions. 

These schemes of expression evaluation are called substitution models. This can be applied to all expressions that do not have side effects (i.g., x++ is a side effect). 

No comments:

Post a Comment