简体   繁体   中英

Increment an element in an Array in F#

This is going to seem incredibly simple and trivial, yet I cannot find any answers on Google this morning for this.

I'm converting this silly bit of C# I produced in just a few minutes to F# (it's an answer to a challenge):

    private static readonly int MaxAge = 131;
    private static int[] Numbers = new int[MaxAge];
    static void Main()
    {
        Random random = new Random(130);
        for ( int i = 1; i < 1000000 - 1; i++) Numbers[random.Next(1,MaxAge )] += 1;
        for ( int i = 1;i <= Numbers.Length - 1; i++) Console.WriteLine( "{0}: {1}", i, Numbers[i]);
        Console.ReadLine();
    }

In F# I'm starting with this:

 let r = new Random()
 let numbers =  Array.create 131 int
 let x = for i in 1 .. 100000  do 
                  let rn =r.Next(1,130)
                  numbers.[rn] <- numbers.[rn] + 1

However, the + 1 produces an error I just can't quite comprehend: Error 1 The type 'int' does not match the type ''a -> int'

My intention is simply to increment the value stored at any given index randomly between 1 and 131 thus simulating a million random integers between 1 and 131 and putting them in buckets.

Can anyone offer me the facepalm moment here please?

You are missing generator function in Array.create returning integer value. 'int' is a function value converting obj to int so you have created array of functions. You can initialize an array just by integer value like

let numbers =  Array.create 131 0

which creates array of zeros. Or you can use any other function, returning int value Also you can generate arrays in F# this way:

let numbers = [|for i in 1 .. 131 -> 0|]

Instead of 0 you also can use any generator function like:

let numbers = [|for i in 1 .. 131 -> i * i|]

But in this case easiest way is

Array.zeroCreate 131

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM