yup and like C#, F# supports both regular and jagged arrays 2D arrays. As the name implies in regular arrays all dimensions have the same length were as with jagged arrays dimensions can be different lengths. See below form the normal way to create them:

1
2
let regular = Array2.create 2 2 1
let jaggedArray = [| [| 1 |]; [| 1; 2 |] |]
By on 7/25/2007 9:22 AM ()

I've got the array created, it's getting a single dimension (which basically means a 1D array) out of it. If you make a 2D array like this:

1
let arr = Array2.create 10 10 0;;

you get, predictably, an 2D array containing ten 1D arrays, all initialized to 0. But if you then try to get the first dimension (the first 1D array) like this:

1
arr.(0);;

which is how you'd do it in C# (specifying only the first index gives you the full array at that index), I get an error saying "This expression has type int [,] but is here used with type 'a array". Am I missing a cast?

DC

By on 7/25/2007 9:33 AM ()

I've got the array created, it's getting a single dimension (which basically means a 1D array) out of it. If you make a 2D array like this:

1
let arr = Array2.create 10 10 0;;

you get, predictably, an 2D array containing ten 1D arrays, all initialized to 0. But if you then try to get the first dimension (the first 1D array) like this:

arr.(0);;

which is how you'd do it in C# (specifying only the first index gives you the full array at that index), I get an error saying "This expression has type int [,] but is here used with type 'a array". Am I missing a cast?

DC

This because Array2.create a regular array, with all deminisions the same size. It only allows access to the individual members. If you look at the type of the object this gives a strong hint on how to access the members, to acess them you use a two deminsional look up .(0,0).

1
2
let regular = Array2.create 2 2 1
let i = regular.(0,0)
By on 7/26/2007 12:34 AM ()

AFAIK you can't get a single dimention like that. Array2 is probably there as a conveniance (so you don't have to simulate a contiguous square array with a flat array + indexing function). As Robert pointed out, the alternative is an array of arrays (aka jagged array). Something like:

1
2
3
4
let arr = Array.create 10 (Array.create 10 0)

arr.(0)

Regards.

--

Ben Jackson.

By on 7/25/2007 12:02 PM ()

You need to be a wee bit careful here as this wont work as expected (all ten elements of the 1st dimension point to the same array).

1
2
3
4
 

let arr2 x y init = Array.init x (fun _ -> Array.create y init)

Cheers,

Andy

By on 7/25/2007 1:05 PM ()

Doh!

I shouldn't have missed that, especially having been bitten by the exact same thing in Ocaml.

By on 7/25/2007 1:52 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper