summaryrefslogtreecommitdiffhomepage
path: root/standard-ml.html.markdown
diff options
context:
space:
mode:
authorJames Baker <j.baker@outlook.com>2015-04-26 10:00:21 +0100
committerJames Baker <j.baker@outlook.com>2015-04-26 10:00:21 +0100
commitf8260574d9a29d5302dccf8fb883d5e3d60592d0 (patch)
treeb281a8dc69f842632d87f5c3c2c00a80a877dc3b /standard-ml.html.markdown
parent02bc5183512e1548bfb3a54bacc85443dc33f86d (diff)
Add examples of imperative-style control
Make reference and update, add use of a while and use of seq
Diffstat (limited to 'standard-ml.html.markdown')
-rw-r--r--standard-ml.html.markdown19
1 files changed, 19 insertions, 0 deletions
diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown
index cc5132f1..8fc849cb 100644
--- a/standard-ml.html.markdown
+++ b/standard-ml.html.markdown
@@ -383,6 +383,25 @@ val test_poem = readPoem "roses.txt" (* gives [ "Roses are red,",
"Violets are blue.",
"I have a gun.",
"Get in the van." ] *)
+
+(* We can create references to data which can be updated *)
+val counter = ref 0 (* Produce a reference with the ref function *)
+
+(* Assign to a reference with the assignment operator *)
+fun set_five reference = reference := 5
+
+(* Read a reference with the dereference operator *)
+fun equals_five reference = !reference = 5
+
+(* We can use while loops for when recursion is messy *)
+fun decrement_to_zero r = if !r < 0
+ then r := 0
+ else while !r >= 0 do r := !r - 1
+
+(* This returns the unit value (in practical terms, nothing, a 0-tuple) *)
+
+(* To allow returning a value, we can use the semicolon to sequence evaluations *)
+fun decrement_ret x y = (x := !x - 1; y)
```
## Further learning