1

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?

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.