Tag standard ml

Mutation Via References

val x = ref 42 val y = ref 42 (* Although the number is the same, x and y do NOT point to the same thing! *) val z = x (* z is now a ...

First Class Functions and Functional Programming

Functions can take other functions as arguments. Consider: fun compose (f, n, x) = if n = 0 then x else f(compose(f, n-1, x)) This calls ...

Tail Recursion

A tail call is when the callee’s result is merely returned without being used (i.e. it is not multiplied or added to anything, etc). In ...

Exceptions

exception MyException exception AnException of int*int raise MyException e1 handle ex => e2 e1 handle ex(x,y) => e2 (* More generally *) ...

Nested Patterns

We can nest patterns as deep as we like. Anywhere we put a variable in our pattern, we can put another pattern. exception BadTriple fun ...

Polymorphic Types and Equality Types

The type ''a represents an equality type: It means anything that can be compared with the equality operator. Not everything can be ...

Functions and Type Inference

If you use patterns to access records or function arguments, you usually do not need to specify their types. They will be inferred from ...

Functions, Pattern Matching And Val Bindings

The pattern {f1=x1, ..., fn=xn} will match against a record (assuming all the types match) {f1=v1,...,fn=vn}. Note that since all tuples ...

Case Expressions

Example (newtype is defined in a previous post). fun f (x : newtype) = case x of Pizza => 3 | Str s => 8 | TwoInts(i1, i2) => i1 + i2 To ...

Datatype Bindings

Example: datatype newtype = TwoInts of int*int | Str of string | Pizza newtype is a new type that is added to the environment. TwoInts, ...

Type Synonyms

type aname = t aname becomes an alias for type t. Useful for giving meaningful names: type date = int*int*int Think of it like typedef ...

Records

Example: val x = {k1=3, k2=false} Ordering of keys does not matter. You can nest records. The type is: {k1:int, k2:bool}. You use #k1 to ...

Immutability

Most of Standard ML has immutability. Behind the scenes, references may be in use for optimization purposes, but the language guarantees ...

Options

Consider this motivating example: I want to write a function that takes a list of integers, and returns its sum. What should it return ...

Let Expressions

Syntax let b1 b2 ... bn in e end The keywords are let, in, end. bi are bindings. e is an expression. Note that often bi are each on ...

Tuples and Lists

Tuples Syntax (e1, e2, ..., en) Note that the length of a tuple is known in advance. Type Checking ei will have type ti (the types need ...

Functions

Defining Functions Look at the following example to declare a function: fun pow(x:int, y:int) = if y = 0 then 1 else x * pow(x, y-1) If ...

Standard ML - Basics

Comments Comments begin with (* and end with *). You can nest comments. Statement Ends In the REPL, each statement must end in a ...