Hi Julien,

You have an optimistic idea of 'very slow' because the F# code never terminates. [:)]

The problem is with this line

1
let x = SHA1.hash x

In C++ this code assigns to the variable x. However in F#, since variables are immutable, this line creates a new variable x that shadows the old variable x. Since you're copying C++ code it would seem reasonable to use a mutable local variable here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let standard_generate_fast_set n  = 
  let allowed = HashSet<int>.Create()
  let mutable x = 
    let ip = [|80uy;4uy;4uy;0uy|]
    Array.append ip [|for i in 0 .. 19 -> 170uy|]
  let count_pieces = 1313u
  let a,b,c = 256u*256u*256u, 256u*256u, 256u
  while allowed.Count < n do
    x <- SHA1.hash x
    for i in 0 .. 4 .. 19 do
      let  y = uint32 x.[ i] * a + uint32 x.[i+1]* b + uint32 x.[i+2]* c + uint32 x.[i+3]
      let idx = y % count_pieces
      allowed.Add(int idx)
  allowed
By on 12/12/2007 4:38 AM ()

Thank you! I have tried your version and it indeed works gnice and fast.

====

In C++ this code assigns to the variable x. However in F#, since variables are immutable, this line creates a new variable x that shadows the old variable x. Since you're copying C++ code it would seem reasonable to use a mutable local variable here.

However, I don't understand why shadowing the "x" variable prevents the function from "ending". The resulting hash that is used afterwards should be the same in both cases (ie whether overwriting the old variable by creating a new one, or by using the mutable assignment) shouldn't it ?

Many thanks,

Julien

By on 12/12/2007 5:52 AM ()

It doesn't overwrite the old variable. There are two immutable variables that happen to have the same name but they are still distinct.

1
let x = SHA1.hash x

The x on the right-side refers to the x that was previously declared. The x on the left-side defines a new variable. Any occurance of x in the scope of this let will refer to this newly defined x and not the outer x.

It is like in C# how in a method you can declare a local variable that has the same name as a field of the class. The local variable shadows the field but they are still separate and unrelated variables.

By on 12/12/2007 6:16 AM ()
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