wmercer
wmercer

Reputation: 1152

Typed Array assignment in F#

Why doesn't this work?

open System
let ary = Array.create<Int16> 10
ary.[0] <- 42 // compiler error
printfn "%d" ary.[0] // compiler error

The error I get is something like:

The operator 'expr.[idx]' has been used on an object of indeterminate type based on information prior to this program point. Consider adding further type constraints

Upvotes: 0

Views: 86

Answers (1)

Matthew Mcveigh
Matthew Mcveigh

Reputation: 5685

The signature for Array.create<'T> is:

Array.create : int -> 'T -> 'T []

Currently you're only providing the first argument (number of elements to create) so ary is actually a function: Int16 -> Int16 []

You need to pass the second argument which is the value to use for the elements in the array:

let ary = Array.create<Int16> 10 0s

If you want the type's default value to be used for all the elements in the array (as it is in the above example) then you can use Array.zeroCreate as @Sehnsucht has pointed out

Upvotes: 2

Related Questions