ML Lecture 3

Identifiers
  1. The val statement associates an identifier with a value (which can be computed from an expression)
  2. The value still has a specific type, even when referenced through the identifier
  3. val pi = 3.14156; means that the identifier pi refers to the real value 3.14156
  4. The identifier can be used in an expression, or in general any place a value of that type can be used
  5. Type consistency is still maintained
  6. Note: unlike other languages you may have used, identifiers are not declared ahead of time to hold specific types; they are simply assigned typed values.
Functions in general
  1. A function is a computation that maps an input domain to an ouput range
  2. In math, the function of a line of slope 2 and y-intercept 3 is f(x) = 2*x + 3
  3. x is an identifier which takes on values in the domain of the function - we call x a parameter of the function f
  4. For a given value of x, f(x) is the value resulting from computing its expression with x being replaced by its value -- e.g., if x is 2 , f(x) is 7 -- we also just simply write f(2)=7
Functions in ML
  1. functions are defined using the fun keyword:
    1. fun square(x:real) = x * x;
  2. because ML is strongly typed, we must tell ML the type of value x will refer to -- hence the need to use the x:real syntax
  3. x is a parameter to the function square -- it is an identifier that refers to a value that the function will use to compute its result
  4. ML responds by telling us square is a function "fn : real -> real" -- what this means is that square takes a real value and results in another real value. The arrow separates the input types (the domain) of the function from the output type (the range)
Defining and Using functions
  1. The definition of a function is done in the fun statement, as above.
  2. A function is used (we say called, or invoked), when it is named in an expression, and values are used in place of each parameter (the values can be existing identifiers, or expressions, but must always be of the correct type).
  3. The use of a function means that the values are used to evaluate the expression in the body of the function, and the computed value is returned to the expression containing the function use.
The scope of parameters
  1. When we use x as a parameter to a function, that use of x only applies to the body of the function
  2. Any other "x" is not affected
Examples on slides are found here