Of syntax and ml

Out of curiosity why the syntax for Discriminating Unions in ML languages

uses the Of Syntax

type Shape =
    | Rectangle of width : float * length : float
    | Circle of radius : float
    | Prism of width : float * float * height : float

why the use of the keyword of and how do you read it or think of it , because it reads weird honestly

Circle of radius

a with key word would have make more sense for example, so why was of choosen

In English it’s not unusual to say:

  • “This is a rectangle of width 5 inches and height 10 inches” rather than “This is a rectangle with a width of 5 inches and a height of 10 inches”, or;
  • “This is a circle of radius 3cm” rather than “This is a circle with a radius of 3cm”.

It’s a slightly ‘older’ (but not archaic or obsolete) and slightly shorter, way of describing things and could have been chosen because mathematics – which programming languages use as a basis – uses forms of description which were decided a long time ago (sometimes hundreds of years or more) but which have ‘stuck’ because they are known and understood within that area of knowledge. (This is the same reason why we have to deal with things called functors, applicatives, monads, etc.)

For example, computational mathematics is the same place we get the word ‘string’ from when talking about an ordered collection of characters. When we talk about a ‘string’ we are not referencing threads twisted together, which most non-programmers would think of, but we all know and understand what a ‘string’ is because we are used to using that term in relation to collections of characters.

(There’s also a chance that using ‘of’ rather than ‘with’ could have made parsing the code easier since ‘with’ is used elsewhere in the language, but that’s a totally wild guess on my part.)

To get the ‘real’ answer you would probably have to ask someone who designed the language, or ask someone who knows someone who did.

As with most things that are weird when you look at them too closely, in the end, you just get used to it and don’t really need think about it too much.

Edit: It should also be considered that the ‘of’ in the type declaration has to (almost) ‘work’ with everything, as in this (very basic) example it ‘works’ just fine:

type Bolt = { Size : int ; Length : int }
type Bolts = Bolt array 
type Washer = { Size : int }
type Washers = Washer array
type Fixings = 
| Box of Bolts 
| Jar of Washers


type Fixings = 
| Box with Bolts 
| Jar with Washers

…doesn’t sound quite right to me.

1 Like