System.Random producing the same random number - random

Despite the Random generator only being created once, the output is always the same random result (for all three test outputs).
A test snippet from a slightly larger script:
let myRandGen = System.Random()
let getRandomObject =
let options = [|"Bob"; "Jim"; "Jane"|]
let randIndex = myRandGen.Next(options.Length)
options.[randIndex]
printfn "New one: %s" getRandomObject
printfn "New two: %s" getRandomObject
printfn "New three: %s" getRandomObject
I need the output to be random for each call, which it currently isn't.
Example output:
New one: Jane
New two: Jane
New three: Jane

Your getRandomObject is a value. It is evaluated once. To fix this, make getRandomObject a function:
let getRandomObject () =
let options = [|"Bob"; "Jim"; "Jane"|]
let randIndex = myRandGen.Next(options.Length)
options.[randIndex]
and call it like so: getRandomObject ()

This works for me:
let myRandGen = System.Random()
let getRandomObject () =
let options = [|"Bob"; "Jim"; "Jane"|]
let randIndex = myRandGen.Next(options.Length)
options.[randIndex]
printfn "New one: %s" (getRandomObject())
printfn "New two: %s" (getRandomObject())
printfn "New three: %s" (getRandomObject())

You generated your random number once, which doesn't change throughout the whole program. To have a new random value after every use, you must re-initialize the random value.

Related

stargazer: line break in F Statistic / df

when creating a table with stargazer, I would like to add a new line befor the degrees of freedom (s. below: before the opening bracket). Could someone help me with the correct call, I couldn't find it in the package documentation. (Apologies for not creating reproducible code, I don't know how to simulate a regression with fake data. I hope someone can still help me!)
As far as I know, there is no built-in functionality to show F-statistics and dfs in distinct lines. You have to hack the output of stargazer() to make a table that you want. A user-defined function in this answer (show_F_in_two_lines()) will produce a table as shown below.
library(stringr)
show_F_in_two_lines <- function(stargazer) {
# `Stringr` works better than base's regex
require(stringr)
# If you remove `capture.output()`, not only the modified LaTeX code
# but also the original code would show up
stargazer <- stargazer |>
capture.output()
# Reuse the index in which F-statistics are displayed
position_F <- str_which(stargazer, "F Statistic")
# Extract only F-statistics
Fs <- stargazer[position_F] |>
str_replace_all("\\(.*?\\)", "")
# Extract only df values and make a new line for them
dfs <- stargazer[position_F] |>
str_extract_all("\\(.*?\\)") |>
unlist() |>
(
\(dfs)
paste0(" & ", dfs, collapse = "")
)() |>
paste0(" \\\\")
# Reuse table elements that are specified
# after the index of F-statistics
after_Fs <- stargazer[-seq_len(position_F)]
c(
stargazer[seq_len(position_F - 1)],
Fs,
dfs,
after_Fs
) |>
cat(sep = "\n")
}
stargazer(
header = FALSE,
lm.out.1,
lm.out.2,
lm.out.3,
lm.out.4,
lm.out.5
) |>
show_F_in_two_lines()

Closures and random numbers in F#

For fun, I am trying to write a simple simulation of the
Monty Hall problem
problem using F#.
I have created a function getShow which returns an array of three booleans (representing doors), one of which is randomly true (it has a car behind it) and the other two false.
let getShow =
let doorWithCar = System.Random().Next(3)+1
[|for door in 1..3 -> door = doorWithCar|]
Now when I try to get a sequence of shows using yield to call the getShow function, I keep getting the first random show repeated (I am guessing because of the way closures work in F#).
let shows =
seq { for i in 1 .. 10 do yield getShow} // Keeps generating the same show over and over
What is the correct way to call the getShow function using yield so that it actually calls the function and gets a new random array?
getShow is a value and not a function, so it's calculated once and you keep yielding the same value. To turn it into a function you have to add (). Also, you keep creating a new Random instance, which is probably initialized with the same time seed, not giving you what you want. Try this instead:
let random = System.Random()
let getShow() =
let doorWithCar = random.Next(3)+1
[|for door in 1..3 -> door = doorWithCar|]
let shows =
seq { for i in 1 .. 10 do yield getShow()}

F#: Attempt to memoize member function resets cache on each call?

I'm trying to memoize a member function of a class, but every time the member is called (by another member) it makes a whole new cache and 'memoized' function.
member x.internal_dec_rates =
let cache = new Dictionary< Basis*(DateTime option), float*float>()
fun (basis:Basis) (tl:DateTime option) ->
match cache.TryGetValue((basis,tl)) with
| true, (sgl_mux, sgl_lps) -> (sgl_mux, sgl_lps)
| _ ->
let (sgl_mux, sgl_lps) =
(* Bunch of stuff *)
cache.Add((basis,tl),(sgl_mux,sgl_lps))
sgl_mux,sgl_lps
I'm using Listing 10.5 in "Real World Functional Programming" as a model. I've tried using a memoization higher-order function and that doesn't help. The above listing has the memoization built in directly.
The problem is, when I call it e.g.
member x.px (basis:Basis) (tl: DateTime option) =
let (q,l) = (x.internal_dec_rates basis tl)
let (q2,l2) = (x.internal_dec_rates basis tl)
(exp -q)*(1.-l)
execution goes to the 'let cache=...' line, defeating the whole point. I put in the (q2,l2) line in order to make sure it wasn't a scope problem, but it doesn't seem to be.
In fact I did a test using Petricek's code as a member function and that seems to have the same issue:
// Not a member function
let memo1 f =
let cache = new Dictionary<_,_>()
(fun x ->
match cache.TryGetValue(x) with
| true, v -> v
| _ -> let v = f x
cache.Add(x,v)
v
)
member x.factorial = memo1(fun y->
if (y<=0) then 1 else y*x.factorial(y-1))
Even the internal recursion of x.factorial seems to set up a new 'cache' for each level.
What am I doing wrong, and how can I make this work?
In response to your comment on Jack's answer, this doesn't have to become tedious. Given a memoize function:
let memoize f =
let cache = Dictionary()
fun x ->
match cache.TryGetValue(x) with
| true, v -> v
| _ ->
let v = f x
cache.Add(x, v)
v
Define each of your functions as let-bound values and return them from your methods:
type T() as x =
let internalDecRates = memoize <| fun (basis: Basis, tl: DateTime option) ->
(* compute result *)
Unchecked.defaultof<float * float>
let px = memoize <| fun (basis, tl) ->
let (q,l) = x.InternalDecRates(basis, tl)
let (q2,l2) = x.InternalDecRates(basis, tl)
(exp -q)*(1.-l)
member x.InternalDecRates = internalDecRates
member x.Px = px
The only "boilerplate" is the let binding and call to memoize.
EDIT: As kvb noted, in F# 3.0 auto-properties allow a more concise solution:
type T() as x =
member val InternalDecRates = memoize <| fun (basis: Basis, tl: DateTime option) ->
(* compute result *)
Unchecked.defaultof<float * float>
member val Px = memoize <| fun (basis, tl) ->
let (q,l) = x.InternalDecRates(basis, tl)
let (q2,l2) = x.InternalDecRates(basis, tl)
(exp -q)*(1.-l)
I see a lot of long answers here; the short answer is that
member x.P = code()
defines a property P which has a getter that runs code() every time P is accessed. You need to move the cache creation into the class's constructor, so that it will only run once.
As others already said, this cannot be done just by defining a single member in F# 2.0. You either need a separate field (let bound value) for a cache or for a local function that is memoized.
As mentioned by kvb, in F# 3.0, you can do this using member val which is a property that is initialized when the object is created (and has an automatically generated backing field where the result is stored). Here is a complete sample that demonstrates this (it will work in Visual Studio 2012):
open System.Collections.Generic
type Test() =
/// Property that is initialized when the object is created
/// and stores a function value 'int -> int'
member val Foo =
// Initialize cache and return a function value
let cache = Dictionary<int, int>()
fun arg ->
match cache.TryGetValue(arg) with
| true, res -> res
| false, _ ->
let res = arg * arg
printfn "calculating %d" arg
cache.Add(arg, res)
res
// Part of the property declaration that instructs
// the compiler to generate getter for the property
with get
The with get part of the declaration can be omitted, but I include it here to make the sample clearer (you can also use with get, set to get a mutable property). Now you can call test.Foo as a function and it caches the value as required
let t = Test()
t.Foo(10)
t.Foo(10)
The only problem with this approach is that t.Foo is actually compiled as a property that returns a function (instead of being compiled as a method). This is not a big problem when you use the class from F#, but it would be a problem if you were calling it from C# (because C# would see the member as a property of type FSharpFunc<int, int>, which is hard to use).
John is correct -- you need to move the cache dictionary into a private, let-bound member of the type.
Type members are compiled a bit differently than let-bound values in modules, which is the reason for the difference in behavior. If you copy/paste the body of your x.internal_dec_rates method and assign it to a let-bound value in a module, it should work correctly then, because the F# compiler will compile it as a closure which gets created once and then assigned to a static readonly field of the module.
A couple of other tips, for good measure:
Type member methods can use optional parameters -- so you can slightly simplify the method signature if you like.
You can create the cache key just once and reuse it (this also helps avoid mistakes).
You can simplify the (sgl_mux, sgl_lps) pattern-matching code by just assigning the tuple a name (e.g., value), since you're just returning the whole tuple anyway.
Here's my take on your code:
type FooBar () =
let cache = new Dictionary< Basis*(DateTime option), float*float>()
member x.internal_dec_rates (basis : Basis, ?tl : DateTime) =
let key = basis, tl
match cache.TryGetValue key with
| true, value -> value
| _ ->
// sgl_mux, sgl_lps
let value =
(* Bunch of stuff *)
cache.Add (key, value)
value
You need to move the dictionary outside the function call - like
let cache = new Dictionary< Basis*(DateTime option), float*float>()
member x.internal_dec_rates =
fun (basis:Basis) (tl:DateTime option) ->
match cache.TryGetValue((basis,tl)) with
| true, (sgl_mux, sgl_lps) -> (sgl_mux, sgl_lps)
| _ ->
let (sgl_mux, sgl_lps) =
(* Bunch of stuff *)
cache.Add((basis,tl),(sgl_mux,sgl_lps))
sgl_mux,sgl_lps
This way the cache persists across the function calls. Your memo1 has the same problem. In the original version, you create a new cache every time you call the function, this way we just have a single cache, which persists across function calls.
In addition to the other answers, note that in F# 3.0 you can use automatically implemented properties, which will behave as you want:
member val internal_dec_rates = ...
Here, the right hand side is evaluated only once, but everything is self-contained.

Scrambled looking records in F#-Interactive

When trying to print
pop
I get all this weird looking formatting in F# interactive, which basically turns the printing useless. Is there someway other to correctly format this?
The code is the following:
#light
open System
let rng = new Random()
type Individual = { x:int; y:int }
type ScoredIndividual = { individual:Individual; score:int }
let genGene() = rng.Next(-10, 10)
let genRandInd() = { x=genGene(); y=genGene() }
let genRandPop popSize = [ for _ in 1 .. popSize -> genRandInd() ]
let getScoredPop f pop = List.map (fun i -> { individual=i; score=(f i)}) pop
let fitnessFun ind = ind.x * ind.x + ind.y * ind.y
let pop = 30 |> genRandPop |> getScoredPop fitnessFun
You can override ToString or use StructuredFormatDisplayAttribute to customize the string representation. This article contains some useful information about customizing output in fsi.
you might want to do fsi.AddPrinter for your ScoredIndividual type to control what's written to the console
That's pretty rough, and I couldn't find any "easy" way to fix it. However, FsEye can make it nicer (while it does delete the newlines, those spaces are in there good):

Wait for any event of multiple events simultaneously in F#

In F# I know how to wait asynchronously for one event using Async.AwaitEvent:
let test = async {
let! move = Async.AwaitEvent(form.MouseMove)
...handle move... }
Suppose I want to wait for either the MouseMove or the KeyDown event. I'd like to have something like this:
let! moveOrKeyDown = Async.AwaitEvent(form.MouseMove, form.KeyDown)
This function doesn't exist but is there another way to do this?
let ignoreEvent e = Event.map ignore e
let merged = Event.merge (ignoreEvent f.KeyDown) (ignoreEvent f.MouseMove)
Async.AwaitEvent merged
EDIT: another version that preserves original types
let merged = Event.merge (f.KeyDown |> Event.map Choice1Of2) (f.MouseMove |> Event.map Choice2Of2)
Async.AwaitEvent merged
EDIT 2: according to comments of Tomas Petricek
let e1 = f.KeyDown |> Observable.map Choice1Of2
let e2 = f.MouseMove |> Observable.map Choice2Of2
let! evt = Observable.merge e1 e2 |> Async.AwaitObservable
AwaitObservable primitive can be taken from here ('Reactive demos in Silverlight' by Tomas Petricek).
I used an implementation of a method that you use in your sample in the talk about reactive programming that I had in London (there is a download link at the bottom of the page). If you're interested in this topic, you may find the talk useful as well :-).
The version I'm using takes IObservable instead of IEvent (so the name of the method is AwaitObservable). There are some serious memory leaks when using Event.merge (and other combinators from the Event module) together with AwaitEvent, so you should use Observable.merge etc. and AwaitObservable instead.
The problem is described in more detail here (see Section 3 for a clear example). Briefly - when you use Event.merge, it attaches a handler to the source event (e.g. MouseDown), but it does not remove the handler after you finish waiting using AwaitEvent, so the event is never removed - if you keep waiting in a loop coded using asynchronous workflow, you keep adding new handlers (that do not do anything when run).
A simple correct solution (based on what desco posted) would look like this:
let rec loop () = async {
let e1 = f.KeyDown |> Observable.map Choice1Of2
let e2 = f.MouseMove |> Observable.map Choice2Of2
let! evt = Observable.merge e1 e2 |> Async.AwaitObservable
// ...
return! loop() } // Continue looping
BTW: You may also want to look at this article (based on chapter 16 from my book).
In the interest of understanding what's going on I looked up the source code to Event.map, Event.merge and Choice.
type Choice<'T1,'T2> =
| Choice1Of2 of 'T1
| Choice2Of2 of 'T2
[<CompiledName("Map")>]
let map f (w: IEvent<'Delegate,'T>) =
let ev = new Event<_>()
w.Add(fun x -> ev.Trigger(f x));
ev.Publish
[<CompiledName("Merge")>]
let merge (w1: IEvent<'Del1,'T>) (w2: IEvent<'Del2,'T>) =
let ev = new Event<_>()
w1.Add(fun x -> ev.Trigger(x));
w2.Add(fun x -> ev.Trigger(x));
ev.Publish
This means our solution is creating 3 new events.
async {
let merged = Event.merge
(f.KeyDown |> Event.map Choice1Of2)
(f.MouseMove |> Event.map Choice2Of2)
let! move = Async.AwaitEvent merged
}
We could reduce this to one event by making a tightly coupled version of this library code.
type EventChoice<'T1, 'T2> =
| EventChoice1Of2 of 'T1
| EventChoice2Of2 of 'T2
with
static member CreateChoice (w1: IEvent<_,'T1>) (w2: IEvent<_,'T2>) =
let ev = new Event<_>()
w1.Add(fun x -> ev.Trigger(EventChoice1Of2 x))
w2.Add(fun x -> ev.Trigger(EventChoice2Of2 x))
ev.Publish
And here is our new code.
async {
let merged = EventChoice.CreateChoice form.MouseMove form.KeyDown
let! move = Async.AwaitEvent merged
}
You can use a combination of Event.map and Event.merge:
let eventOccurs e = e |> Event.map ignore
let mouseOrKey = Event.merge (eventOccurs frm.MouseMove) (eventOccurs frm.KeyDown)
Then you can use Async.AwaitEvent with this new event. If MouseMove and KeyDown had the same type, you could skip the Event.map step and just directly merge them.
EDIT
But at Tomas points out, you should use the Observable combinators in preference to the Event ones.

Resources