Array Constants or Initialization
Creating Pre-initialized Arrays in other languages:
C, C++, Java, C#:
int a[] = {1, 2, 3, 4};
Rust
let a = [1i32, 2i32, 3i32, 4i32];
Scala
val a = Array(1, 2, 3, 4)
Go
a := []int{1, 2, 3, 4}
Swift
let a = [1, 2, 3, 4]
Perl
@a = (1, 2, 3, 4);
Lua
a = { 1, 2, 3, 4 }
Python, Ruby, Groovy, node.js
a = [1, 2, 3, 4]
Haskell / Prolog / Erlang / Elixir
[1, 2, 3, 4]
F#
[1; 2; 3; 4]
Ada
A: array(1..4) of Integer := (1, 2, 3, 4);
Fuzions Approach to Pre-initialized arrays
Pre-initialized Arrays
Basic ideas:
- brackets
[ ]seem most popular and go well with using brackets to access an element as ina[i]. - Requiring a type identifier is awkward.
- The type should be inferred from the array elements.
- If array is assigned to a field, that field's type can be used to infer the type instead.
- The resulting arrays should be immutable, persistent arrays
- In case elements are mutable, we need new instances of the arrays for every use.
So, in Fuzion, we would have:
a := [1, 2, 3, 4] # array of default integer type (i32 or i64, need to decide)
b array u16 := [1, 2, 3, 4] # array of u16, inferred from field b
write(bytes array u8) is ...
write [1, 2, 3, 4] # array of u8 inferred from field write.bytes
ix := 2
c := [1, 2, 3, 4][ix] # array of default integer type (i32 or i64, need to decide)
ix := 2
d i64 := [1, 2, 3, 4][ix] # array of default integer type, 3 will be converted to i64
e i16 := [1, 2, 3, 4][ix] # array of default integer type, error since not assignable to i16
f := [1, true, "abc"] # array of Object, boxed elements
g := [1, true, 3] # array of Object, boxed elements
h array (i32 | bool) := [1, true, 3]
# array of i32 | bool, no boxing but tagged choice values
Pre-initialized Lists
Lists (unions of nil and a Cons A
(list A) cell) also need syntactic sugar for initialization.
Since array is convertible to list via array.as_list,
it would be convenient to just stick with the same syntax for pre-initialized
lists:
l := [1, 2, 3, 4].as_list # list of default integer type (i32 or i64, need to decide)
m list i32 := [1, 2, 3, 4] # list of i32, implicit call to as_list
The type inference for initialized arrays should work for lists as well:
write_list(bytes list u8) is ...
write_list [1, 2, 3, 4] # list of u8 inferred from field write_list.bytes
f list Object := [1, true, "abc"]
# list of Object, boxed elements
g := [1, true, 3].as_list # list of Object, boxed elements
h list (i32 | bool) := [1, true, 3]
# list of i32 | bool, no boxing but tagged choice values