Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

defining a new array of a specific type on F#

Tags:

arrays

f#

How can I specifically define a new array of a specific type T ?

Strangely, I couldn't find any helpful information about it..

I want to write something like this:

let arr = new Array()

only that the elements of arr must be of type T.

How can I do it on F# ?

like image 305
cookya Avatar asked Jun 15 '12 11:06

cookya


2 Answers

Maybe the Array.init<'T> and Array.create<'T> functions are what you are looking for.

Also consider using a Sequence instead of an array.

A sequence is a logical series of elements all of one type. Sequences are particularly useful when you have a large, ordered collection of data but do not necessarily expect to use all the elements.

like image 119
Dennis Traub Avatar answered Oct 12 '22 23:10

Dennis Traub


If type of elements is unknown, you can use explicit type annotation:

let arrayOfTenZeroes = Array.zeroCreate<int> 10    
let emptyIntArray: int array = [||]

When you use high-order functions from Array module, you don't have to do so since type of elements is automatically inferred by the type checker:

// arr is inferred as int array
let arr = Array.init 10 (fun i -> i+1)
like image 39
pad Avatar answered Oct 12 '22 23:10

pad