-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtype_safety.fun
More file actions
executable file
·101 lines (80 loc) · 2.22 KB
/
type_safety.fun
File metadata and controls
executable file
·101 lines (80 loc) · 2.22 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#!/usr/bin/env fun
/**
* This file is part of the Fun programming language.
* https://fun-lang.xyz/
*
* Copyright 2025 Johannes Findeisen <you@hanez.org>
* Licensed under the terms of the Apache-2.0 license.
* https://opensource.org/license/apache-2-0
*/
// Type Safety demonstration in Fun
print("== Dynamic variable (untyped) ==")
x = 100
print(typeof(x)) // -> "Number"
print(x) // -> 100
x = "hello"
print(typeof(x)) // -> "String"
print(x) // -> "hello"
print("")
print("== Typed variables remain type-stable ==")
// Strings must always be strings
string s = "hello"
print(typeof(s)) // -> "String"
print(s) // -> "hello"
// s = 42 // Uncomment to see runtime TypeError: expected String
// Booleans are Numbers constrained to 0 or 1 (clamped)
boolean flag = 0
print(typeof(flag)) // -> "Number"
print(flag) // -> 0
flag = 2 // will be clamped to 1
print(flag) // -> 1
// flag = "no" // Uncomment to see runtime TypeError: expected Number for boolean
// number is a signed 64-bit integer and must remain Number
number n = 123
print(typeof(n)) // -> "Number"
n = 456
print(n) // -> 456
// n = "oops" // Uncomment to see runtime TypeError: expected Number
print("")
print("== Integer width clamping ==")
// Signed 8-bit: range [-128..127]
int8 si = 130 // clamps to 127
print(si) // -> 127
si = -200 // clamps to -128
print(si) // -> -128
// Unsigned 8-bit: range [0..255]
uint8 u = 255
print(u) // -> 255
u = 300 // clamps to 255
print(u) // -> 255
// u = "bad" // Uncomment to see runtime TypeError: expected Number
print("")
print("== Nil-typed variables must stay Nil ==")
nil nn = nil
print(typeof(nn)) // -> "Nil"
// nn = 0 // Uncomment to see runtime TypeError: expected Nil
print("")
print("Done. Uncomment lines above to see type errors in action.")
/* Expected output:
== Dynamic variable (untyped) ==
Number
100
String
hello
== Typed variables remain type-stable ==
String
hello
Number
0
0
Sint64
456
== Integer width clamping ==
-126
56
255
44
== Nil-typed variables must stay Nil ==
Nil
Done. Uncomment lines above to see type errors in action.
*/