summaryrefslogtreecommitdiff
path: root/chapter13/README.md
blob: 892f71701ff74a4d325a914133889f48173e623c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# Chapter 12: Floats, References and Arrays

In this chapter we add a series of new types and some modest syntax.

## Floats

Floating point values start with the `flt` type and compute IEEE754 64-bit arithmetic.
Integer expressions auto-widen to floats when involved in a float expression.

```java
flt f = 0.5;
int x = 2;
f = f+x;     // Auto-widen x to 2.0, result is 2.5
f = f+true;  // Since bools are just synonyms for integers 0,1 they auto-widen also
```


Here is Newton's method to a square root:
```java
flt guess = arg;  // Initial guess is just argument
while( true ) {
    // Next guess from Newton's method
    flt next = (arg/guess + guess)/2;
    // Break if hit fixed point
    if( next == guess ) break;
    guess = next;
}
return guess;
```
When run with argument 2.0, produces 1.414213562373095.

Floating point operations have their own Nodes:

| Node                   | Op                   |
|------------------------|----------------------|
| AddF, SubF, MulF, DivF | Basic binary FP ops  |
| MinusF                 | Unary negate         |
| EQF, LTF, LEF          | FP compare operators |

And their own section in the Type lattice:

Within the Type Lattice, we now add the following domain:

* Float type - Float values.  The same shape as the Integer values, but floats
  with a TOP, BOT and constants


## References

Structs can reference other structs; references can be mutually recursive.
Any reference field can allow null or not, same as a normal variable.

```java
struct Person {
  String name;       // No string type, yet
  int age;
  FamilyTree tree?;  // A family tree, or not
}
struct FamilyTree {
  Person father?;    // FamilyTree can reference Person
  Person mother?;
  Person []kids?;
}
```

Normal field syntax works:  
e.g. `person.tree.father = new Person;` or 
     `person.tree.father.name = "Dad";`.

Reference fields all start out null, and can be tested as such.  However, a
non-null reference field can only be stored with a non-null ref.

```java
struct N { N next; int i; }
N n = new N;
return n.next;  // Value reports as null, despite field typed as not-null
```

And:

```java
struct N { N next; int i; }
N n = new N;
n.next = null; // <<-- Compile error, cannot store null into not-null field
return n.next;
```