ML Lecture 2
Review: Operators
- Arithmetic, string, relational, logical
Review: Types
- All values have a type
- Integer (int), real, string, boolean (bool)
If-then-else Operator
- An operator? Yes, it takes operands and evaluates to a result
- The form is if expr1 then expr2 else expr3;
- expr1 must result in a Boolean value
- expr2 and expr3 must result in values of the same type
- The result of the if-then-else operator is the value of expr2 if expr1
is true, otherwise it is the value of expr3; the type of the result is
the type of expr2 and expr3
- Think about disjoint functions in math
Type consistency
- ML is a strongly typed language
- Every operator (and function) has a specific type signature,
and this cannot be violated.
- For example, the operator ^ (which concatenates two strings)
has a type signature of string*string->string
- reads as "takes a string and another string, and results in a
string".
- order is important for the *
- What about +? We used it with both integers and reals. What
is its type signature?
- it has two: int*int->int and real*real->real
- but not int*real or real*int!
- we say that + is an overloaded operator, because it
has more than one signature
- Resulting types do not have to be the same as the argument types. The
type signatures of the overloaded relational operator > are:
- int*int->bool
- real*real->bool
- string*string->bool
- The type signature of the if-then-else operator is bool->(some
type)
Type conversion (coercion)
- Values can be converted between types
- Think of the coercion as a function taking one argument of a type,
and returning a value of another type.
- Easiest: integer to real: real(3) is 3.0
- What about real to integer: depends on how you want it:
- floor, ceil (ceiling), trunc (truncate)
- floor moves left on the number line
- ceil moves right
- trunc moves towards 0
- note that none of these does rounding
- character to integer? integer to character?
- string to integer? real to string?
Identifiers
- The val statement associates an identifier with a value (which
can be computed from an expression)
- The value still has a specific type, even when referenced through the
identifier
- val pi = 3.14156; means that the identifier pi refers
to the real value 3.14156
- The identifier can be used in an expression, or in general any place
a value of that type can be used
- Type consistency is still maintained
- 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.
Examples on slides are found here