Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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:

  • you declare an array with [| ... |] but it is displayed as [ ... ] in the type
  • you declare a list with [ ... ] but it is displayed as x list in the type

Another example:

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

Why is it like this?

like image 901
Thomas Avatar asked Jan 25 '23 11:01

Thomas


2 Answers

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.

like image 158
Tomas Petricek Avatar answered Jan 27 '23 01:01

Tomas Petricek


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.

like image 33
Brian Berns Avatar answered Jan 27 '23 00:01

Brian Berns