SML# Document Version 4.0.0
7 Introduction to ML programming

7.17 let expressions

ML programming is done by defining an expression and giving a name to it for subsequent use. Examples we have seen so far, names are all recorded at the top-level. However, a large program requires a large number of names, many of which are only temporarily used. For example, fact function in the previous section is defined using loop function, but this name loop is only used in fact; other function would need another version of loop. Such a name should be defined as a local name to the function that use the name. For this purpose, ML provide the following let expression.

expr  ::=
 | let decl_list in expr end
decl  ::= val x = expr
 | fun f p1 xn = expr
 |

The declarations written between let and in are only visible to the code between in and end. A tail recursive fact function is usually written as follows.

  fun factorial n =
    let
      fun loop (s, 0) = s
         | loop (s, i) = loop (s * i, i - 1)
    in
      loop (1, n)
    end