with the following:
let a = "hello world".Split(' ')
the return type is a string array, but the type is written as:
System.String[]
I'm not understanding why:
[| ... |]
but it is displayed as [ ... ]
in the type[ ... ]
but it is displayed as x list
in the typeAnother example:
([| 3 |]).GetType()
val it : System.Type =
System.Int32[]
Why is it like this?
This is an inconsistency that is probably a result of the fact that F# is a .NET language.
In F#, you want lists more often than arrays, so it makes sense to use a shorter syntax [ ... ]
for lists and longer syntax [| ... |]
for arrays.
In .NET, array types are written as System.Int32[]
. This is what you get from GetType
and there is no way F# can override this, because it's coming from the .NET library.
As for the type names, you can always use 'a list
and 'a array
if you want to write types explicitly.
The most inconsistent features is the fact that you can write an array type such as int[]
in F# too. I agree this is confusing. I think F# simply adopted the notation used in C# here. However, note that this also lets you define multi-dimensional arrays easily like int[,]
and int[,,]
. I don't think there is other syntax for multi-dimensional array types.
I think there are reasons for this, but they're not very satisfying:
Types and values are not written the same way. For example, a tuple type is written as 'A * 'B
, while a tuple value is written (a, b)
. Some of us might've preferred ('A, 'B)
for the type as well, but F# is actually consistent with how product types/values are represented mathematically.
Lists are more fundamental to functional programming than arrays, so it makes sense that fewer keystrokes are needed to write a list than to write an array.
F# inherited OCaml conventions, and adapted them to .NET, sometimes awkwardly. The type of [| 1; 2; 3 |]
in OCaml is int array
. F# accepts the .NET/C# name int[]
as well, which is confusing, but you can still use the OCaml syntax in your code if you want: let arr : int array = Array.empty
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With