Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array covariance in F#

Since .NET arrays are covariant, the following works in C#:

var strArray = new string[0];
object[] objArray = strArray;

In F#, given an array, 'T[], what would be the best way to convert it to obj[], without re-creating the array (e.g., Array.map box)? I'm using (box >> unbox), but it feels sloppy.

like image 777
Daniel Avatar asked Sep 07 '11 18:09

Daniel


2 Answers

As Brian says, there's nothing wrong with box >> unbox, other that the fact that array covariance is inherently broken (e.g. ([| "test" |] |> box |> unbox<obj[]>).[0] <- obj() will throw an ArrayTypeMismatchException when trying to perform the assignment).

Instead, you would probably be better off treating a string[] as an obj seq, which is perfectly safe (although it still requires boxing and unboxing in F# since F# doesn't support generic co/contra-variance). Unfortunately, you do lose random access if you go this route.

like image 86
kvb Avatar answered Sep 23 '22 19:09

kvb


box >> unbox

seems like a good idea; O(1), and does the job, apparently.

Consider also not using this CLR mis-feature. ;)

like image 34
Brian Avatar answered Sep 21 '22 19:09

Brian