Coursera-Programming Language Week3

In Week3, the course first covers the two data structure record and tuple in SML . The record is quite like a dict in Python and is an implementation of HashMap. In addition, record has some modern language(ES7+, Kotlin, Go and Rust) features like auto unpacking the record and default value. Also, one interesting feature is that we can use record to represent the tuple like:

val a = {1=1, 2=2}  a = (1,2) //True  

After that, we come to learn what is DataType and case expression in SML. The syntax for this two is quite simple DataType is quite like what we do in C with typedef. While, DataType is more powerful with the case expression which will allow program to deal with different cases with a given DataType:

datatype id = StudentNum of int   
| Name of string * (string option) * string //name tuple

Above code will give you a new type id with two possible form, 1) an int of studentNum or 2)an tuple of string describing the name.

case id of 
StudentNum i => i Name s => #1 s

The above code, will either return the student id or the student first name based on what kind of id is input.
In addition, the class covers a new way of doing recursion that is tail recursion. Compared with oridinary recursion, tail recursion will cut down the stack depth. From my understand, it is because tail recursion will carry the result with doing the recursion while the oridinary recursion need to trace back to get the result.

fun fact x = if n = 0 then 1 else x*fact(x-1) //recursion  
fun fact(x, acc) = if n = 0 then acc else fact(x-1, acc*x) //tail recursion