MLton 20100608 TipsForWritingConciseSML
Home  Index  
SML is a rich enough language that there are often several ways to express things. This page contains miscellaneous tips (ideas not rules) for writing concise SML. The metric that we are interested in here is the number of tokens or words (rather than the number of lines, for example).

Datatypes in Signatures

A seemingly frequent source of repetition in SML is that of datatype definitions in signatures and structures. Actually, it isn't repetition at all. A datatype specification in a signature, such as,

is just a specification of a datatype that may be matched by multiple (albeit identical) datatype declarations. For example, in

the types AnExp.exp and AnotherExp.exp are two distinct types. If such generativity isn't desired or needed, you can avoid the repetition:

Keep in mind that this isn't semantically equivalent to the original.

Clausal Function Definitions

The syntax of clausal function definitions is rather repetitive. For example,

is more verbose than

For recursive functions the break-even point is one clause higher. For example,

isn't less verbose than

It is quite often the case that a curried function primarily examines just one of its arguments. Such functions can be written particularly concisely by making the examined argument last. For example, instead of

consider writing

Parentheses

It is a good idea to avoid using lots of irritating superfluous parentheses. An important rule to know is that prefix function application in SML has higher precedence than any infix operator. For example, the outer parentheses in

are superfluous.

People trained in other languages often use superfluous parentheses in a number of places. In particular, the parentheses in the following examples are practically always superfluous and are best avoided:

The same basically applies to case expressions:

It is not uncommon to match a tuple of two or more values:

Such case expressions can be written more concisely with an infix product constructor:

Conditionals

Repeated sequences of conditionals such as

can often be written more concisely as case expressions such as

For a custom comparison, you would then define an appropriate datatype and a reification function. An alternative to using datatypes is to use dispatch functions

where

An advantage is that no datatype definition is needed. A disadvantage is that you can't combine multiple dispatch results easily.

Command-Query Fusion

Many are familiar with the [WWW]Command-Query Separation Principle. Adhering to the principle, a signature for an imperative stack might contain specifications

and use of a stack would look like

or, when the element needs to be named,

For efficiency, correctness, and conciseness, it is often better to combine the query and command and return the result as an option:

A use of a stack would then look like this:


Last edited on 2007-02-12 07:34:53 by VesaKarvonen.