Note that there are some explanatory texts on larger screens.

plurals
  1. POTurn Off FSharp Function Caching for Specific Function?
    primarykey
    data
    text
    <p>I recently ran into an interesting but annoying F Sharp behavior. According to [1], “F# automatically caches the value of any function which takes no parameters.” This seems like a good idea, but it is causing problems for me as I try to come up with a wrapper function to generate random numbers.</p> <p>As an example, I have two different functions in the code at the end of this question. The first function “getRand” takes no parameters, but unfortunately it always returns the same number. The second function “getRand2” works as I would expect generating a new random number each time it is called, but it annoyingly takes a useless and ignored extra parameter.</p> <p>If possible, I would like to have the functionality of getRand2 but the convenience of getRand. Is there a compiler directive or special keyword I can apply to getRand that will turn off its function caching capabilities and thereby cause it to behave like getRand2?</p> <p>With Thanks,</p> <p>Shawn<br> Note: Forgive me if the answer already appears in [1], I’m just not seeing it right now.<br> [1] - <a href="http://en.wikibooks.org/wiki/F_Sharp_Programming/Caching" rel="nofollow">http://en.wikibooks.org/wiki/F_Sharp_Programming/Caching</a></p> <pre><code>(* Always returns the same number *) let getRand = let seed = int32(System.DateTime.Now.Ticks) let randGen = new System.Random(seed) randGen.Next() (* Works as expected except I need an annoying extra parameter *) let getRand2 dummyParam = let seed = int32(System.DateTime.Now.Ticks) let randGen = new System.Random(seed) randGen.Next() (* Outputs three "identical" numbers to console *) System.Console.WriteLine( "Parameterless getRand always outputs same number.") System.Console.WriteLine(getRand) System.Threading.Thread.Sleep(100) System.Console.WriteLine(getRand) System.Threading.Thread.Sleep(100) System.Console.WriteLine(getRand) System.Console.WriteLine() (* Outputs three "different" numbers to console *) System.Console.WriteLine( "GetRand2 works as expected even though second dummy param is always the same.") System.Console.WriteLine(getRand2 0) System.Threading.Thread.Sleep(100) System.Console.WriteLine(getRand2 0) System.Threading.Thread.Sleep(100) System.Console.WriteLine(getRand2 0) System.Console.WriteLine() </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload