Heisenbug
Heisenbug

Reputation: 39164

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?

Upvotes: 1

Views: 296

Answers (3)

BLUEPIXY
BLUEPIXY

Reputation: 40145

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

anotation omission

let create2DArrayOfT<'T> (row, col) = Array2D.init<'T option> row col (fun _ _ ->None)

usage:

let a = create2DArrayOfT<T>(2,3)

Upvotes: 1

J D
J D

Reputation: 48687

The type of a 2D array is written 'a [,] in F#. Next time, you can find this out using F# interactive by looking at the type of the functions in the Array2D module:

> Array2D.create;;
val it : (int -> int -> 'a -> 'a [,]) = <fun:clo@4>

Upvotes: 4

Ankur
Ankur

Reputation: 33637

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)

Upvotes: 3

Related Questions