Question

I have a function where I add some elements into an array in the following way:

let mutable result = Array.CreateInstance(typeof<int>, arrayA.Length + arrayB.Length)
....
result.SetValue(arrayA.[iidx], kidx)
....

This works, at least in my eyes(just started days ago with F# ...)

The problem is when I call the function and the result should be int[] and it returns an Array. If I am not wrong, obviously because Array.CreateInstance creates an Array, but I thought Array will be 'compatible' with int[] in my case.

This expression was expected to have type
  int[]
but here has type
  Array

How could I cast Array to int[]? Or what should be the best approach for this kind of work with an int[] where I need to edit some specific indexes before returning it.

Was it helpful?

Solution

Instead of using Array.CreateInstance you can use the Array module to create a new array:

let mutable result = Array.create (arrayA.Length + arrayB.Length) 0
result.[kidx] <- arrayA.[iidx]

OTHER TIPS

The reason why you are getting an error is that the CreateInstance method returns System.Array, which is the base class of all .NET arrays. This is probably because the method has been in .NET since before generics existed and so there was no way to make it statically type safe.

If you wanted to use it, you could cast the result to a typed int array int[]:

let result = Array.CreateInstance(typeof<int>, 10) :?> int[]
result.[index] <- 42

Note that you also do not need mutable, because you are not mutating the variable - you are only mutating the object that the variable refers to.

I hope this clarifies why you are getting the error - but as @Lee correctly points out, the F# library provides a much nicer API for working with arrays, which is the Array module - so I'd certainly recommend using Array.create (or Array.zeroCreate or Array.init) when programming in F#.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top