Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SML record subset and update

Tags:

sml

Is there an more straight forward way (and less error prone due to maintenance and amount of editing involved), to achieve the same as below, that is: 1) getting a subset of the elements of a record, given the names list of members of interest, 2) and updating a record from a subset record, using the names of the subset record?

val r = {a = 1, b = 2, c = 3, d = 4, e = 5}
val s = {b = #b r, c = #c r, d = #d r}
val r = {a = #a r, b = #b s, c = #c s, d = #d s, e = #e r}

What I expect, could look like this:

val r = {a = 1, b = 2, c = 3, d = 4, e = 5}
val s = #(b, c, d) r
val r = r / s

As Sebastian Paaske Tørhol said, one can extract part of a record this way:

val {b, c, d, ...} = r

Unfortunately, this does not bind the subset to a single name, as this, as an example, does not work:

val s = {b, c, d, ...} = r
like image 789
Hibou57 Avatar asked Jul 24 '14 00:07

Hibou57


2 Answers

No, there isn't. There once was a proposal for more extensive record operations (Functional record extension and row capture), as part of the short-lived successor ML effort. With that, you could have written, e.g.,

val r = {a = 1, b = 2, c = 3, d = 4, e = 5}
val {a, e, ... = s} = r
val t = {a = a+1, e = e-1, ... = s}

Unfortunately, nobody ever implemented it in a real compiler.

like image 145
Andreas Rossberg Avatar answered Nov 15 '22 11:11

Andreas Rossberg


You can use pattern-matching to extract relevant parts of records:

Example:

val question = { title = "SML record subset and update",
                 author = "Hibou57",
                 tags = ["SML"] }

val { title = t, tags = ts, ... } = question

This binds title into t and tags into ts.

You can also simply omit the names, if you so desire:

val { title, tags, ... } = question

This binds the title to title and tags to tags.

As far as updating goes, Standard ML sadly doesn't have a nice way to update records without explicitly having to set every field.

like image 37
Sebastian Paaske Tørholm Avatar answered Nov 15 '22 10:11

Sebastian Paaske Tørholm