5. Constant definition

5.1. Constant (immutable) variable

Constant variable can be defined following:

1
2
3
4
5
6
7
(* File: val_pi.dats *)
#include "share/atspre_staload.hats"

implement main0 () =
  let val pi = 3.1415 in
    println! (pi * 2)
  end
$ patscc val_pi.dats
$ ./a.out
6.283000

Also we can define it using {}.

1
2
3
4
5
6
7
(* File: val_pi2.dats *)
#include "share/atspre_staload.hats"

implement main0 () = {
  val pi = 3.1415
  val () = println! (pi * 2)
}

The constant variables should not be changed, but able to be overwrited.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
(* File: val_overwrite.dats *)
#include "share/atspre_staload.hats"

implement main0 () = {
  val a = 1
  val b = a
  val () = println! a
  val () = println! b
  val a = 2
  val () = println! a
  val () = println! b
}

First, this program creates a binding between a and 1. Secondly, it creates another binding between b and old a. Finally, it creates new binding between new a and 2.

At line number 7 of val_overwrite.dats, println! shows a value of old a. On the one hand, at line number 10, it shows a value of new a.

$ patscc val_overwrite.dats
$ ./a.out
1
1
2
1

The name binding of code val_overwrite.dats is represented as following figure:

_images/name_binding.png

Note

Exercise: Define following constant variables on ATS language, and print it on console.

  1. The name is e and the value is \(2\).
  2. The name is positive and the value is \(e > 0\).
  3. The name is seconds_of_day and the value is \(60 * 60 * 24\).
  4. The name is name and the value is a char string "John".

5.2. (Mutable) variable

Mutable variable is ready on ATS language, however it’s rarely used on ATS programming.