Thomas
Thomas

Reputation: 12107

Why is an array type written as if it was a list, in F#?

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:

Another example:

([| 3 |]).GetType()
val it : System.Type =
  System.Int32[]

Why is it like this?

Upvotes: 5

Views: 145

Answers (2)

Brian Berns
Brian Berns

Reputation: 17038

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.

Upvotes: 4

Tomas Petricek
Tomas Petricek

Reputation: 243061

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.

Upvotes: 6

Related Questions