Search code examples
multidimensional-arraysyntaxf#option-type

Syntax for declaring a function returning a 2DArray in F#


I need to declare a function in F# that takes 2 parameters (row, col) and return an 2-dimensional array of Option (intitializing all elements to be none), but I don't know the right syntax. I've tried something like:

type T = 
  {
   ....//my type
  }

let create2DArrayOfT (row : int , col: int) Array2D<Option<T>> = Array2D.init<Option<T>> 10 10 (fun -> None)

the signature above is wrong in specifing the return type. So I have 2 questions:

  1. What's the right signature for specifying the return type as a 2-dimensional array?
  2. I've tought to use Option for the elements of my array because I want it to allow some locations to be empty. Is this reasonable?

Solution

  • You don't need to specify return type as that will be deduced by type inference. Just use:

    type T = {Name : string}
    let create2DArrayOfT (row : int , col: int) = Array2D.init<Option<T>> 10 10 (fun _ _ -> None)
    

    UPDATE:

    If you want specify return type use:

    let create2DArrayOfT (row : int , col: int) : Option<T> [,] = Array2D.init<Option<T>> 10 10 (fun _ _ -> None)