I have the following function in F#:
let randomCh () =
let random = Random()
alph.Chars (random.Next (alph.Length - 1));
This function returns same value each time. I had same problem in C#, and solution very simple: create just one Random object like this:
var rnd = new Random();
for (int i = 0; i < 10; i++)
Console.WriteLine(rnd.Next(10));
How can I reach same behaviour in F#: get each time random value?
Well your C# code doesn't define a function whereas your F# does; you could have the same problem in C#. You should either refactor your random definition out of the randomCh function, or bind randomCh to a function after initializing random:
let alph = "abcdefg"
let randomCh =
let random = Random()
fun () -> alph.Chars (random.Next (alph.Length - 1))
printfn "%O" <| randomCh()
printfn "%O" <| randomCh()
Just like in C#, you should pull the creation of the random outside of your function. This will prevent you from creating a new Random generator each call. By default, Random uses the current system clock to seed itself - if you call a function, with the random instance inside of it, quickly in succession, you can seed the random with the same time stamps, effectively giving you the same sequence.
By moving it outside of the function, you will reuse the same random instance, and avoid that:
let random = Random()
let randomCh () =
alph.Chars (random.Next (alph.Length - 1));
// Calling randomCh() repeatedly will now give different values each time
Related
i'm trying to develop the algorithm W in f# for type inference, but i would like to understand how to write the function for generating fresh variables properly.
Actually my function is
let counter = ref -1
let generate_fresh_variable () : string =
let list_variables = ['a' .. 'z'] |> List.map string
counter.Value <- !counter + 1
list_variables.Item(!counter)
but i'm not satisfy with this solution, someone can give me other better ideas?
If you really want to do this with an impure function, I would write it like this:
let mutable counter = -1
let generate_fresh_variable () =
counter <- counter + 1
counter + int 'a'
|> char
|> string
Notes:
Reference cells are obsolete. If you need impurity, use mutable variables instead. (Alternatively, if you really want to stick with a reference cell, the canonical way to update it is with :=, rather than assigning directly to the underlying Value.)
There's no need to maintain a list of potential variable names (and there's especially no need to rebuild the entire list each time you generate a fresh variable).
What happens if you need more than 26 variables?
If you wanted to use some more sophisticated F# tricks, you could create an inifinte sequence of names using a sequence expression (which makes it very easy to handle the looping and dealing with >26 names):
let names = seq {
for i in Seq.initInfinite id do
for c in 'a' .. 'z' do
if i = 0 then yield string c
else yield string c + string i }
A function to get the fresh name would then pick the next name from the sequence. You need to do this using the underlying enumerator. Another nice trick is to hide the state in a local variable and return a function using lambda:
let freshName =
let en = names.GetEnumerator()
fun () ->
ignore(en.MoveNext())
en.Current
Then just call freshName() as many times as you need.
I wrote the following code to test some MonteCarlo code in F#.
My problem is I only see the random numbers and the "oi" once in my console. I call two times the oneRun function, but it looks that it only runs once.
Here is the code:
let genRandomNumbers count =
let rnd = System.Random()
printf "oi "
List.init count (fun _ -> rnd.NextDouble ())
let oneRun =
let numberofClicks = 0
let randomNumber = genRandomNumbers 50
let action numberofClicks random = if random <= 0.10
then numberofClicks+1
else numberofClicks
randomNumber |> Seq.iter (printf "%f ")
randomNumber |> List.fold action numberofClicks
[<EntryPoint>]
let main argv =
let a = oneRun
printf "%d " a
let b = oneRun
printf "%d " b
let key_info = Console.ReadKey()
0 //
Any hints? Ideas?
To expand a little on Mankarse's correct comment, the F# syntax for defining values and functions looks very similar, so it's easy to get confused between them.
This is a value:
let sum = 42
This is a function:
let addThree x = x + 3
Both values and functions can have blocks following them, not just single lines:
let sumWithSideEffects =
// This will only be evaluated once
printfn "Side effect happens here"
42
let addThree x =
// This will run every time you call the function
let result = x + 3
printfn "Added three to %d and got %d" x result
result
A let declaration that just declares a name is a value. Values are only evaluated once, so any side effects in the value will happen just once. Exactly when they happen is not defined precisely by the language spec, so you can't count on when the side effects will happen. Functions, on the other hand, are evaluated every time the function is called.
Now, when you have a function that takes no parameters, how do you declare it? Well, you declare it by giving it a parameter, but a parameter that doesn't matter. Specifically, you declare that it takes a parameter of type unit. The unit type is a special type in F#. It basically corresponds to an empty tuple, and is written as ().
Think about the empty-tuple type for a minute. If you have a tuple of two bool values, how many possible values can this tuple have? Four: it could be (false, false), or (false, true), or (true, false), or (true, true). If you have a tuple of just one bool, it could have two values: (true) or (false). If you have a tuple of zero values (of whatever type: bool, int, string, doesn't matter), then there's only one possible value it could have: (), the empty tuple. And since that's a type with only one possible value, that's why it's called the unit type.
So if you want a function rather than a value, but that function doesn't need to take any meaningful parameters, you define it like this:
let myFunction () =
printfn "I'm being called purely for the side effects"
Note how I put a space between the function name and the unit parameter. You don't actually have to have that space there — it's perfectly legal to write let myFunction() = ... — but I want you to see that the () is not just function-declaration syntax, it's an actual value of an actual type. This distinction becomes important when you start doing advanced things with functions, so I want you to be clear about it now.
BTW, normally you'd have a parameter name in your function declaration rather than a value, but the unit type is treated specially: since there's only one possible value of unit, you already know what value your function will be called with, so you don't really need to assign that to a name anyway. So F# lets you declare a function whose input type is unit by just having a () in the parameter list, instead of making you choose a name that you'd never actually use in the function body.
I hope this clears things up for you.
I am trying to use the Math.NET numerics implementation of the FFT algorithm, but I must be doing something wrong because the output is always unit
The following is the the setup:
open MathNet.Numerics
open MathNet.Numerics.Statistics
open MathNet.Numerics.IntegralTransforms
let rnd = new Random()
let rnddata = Array.init 100 (fun u -> rnd.NextDouble())
let x = rnddata |> Array.Parallel.map (fun d -> MathNet.Numerics.complex.Create(d, 0.0) )
then when I run this:
let tt = MathNet.Numerics.IntegralTransforms.Fourier.BluesteinForward(x, FourierOptions.Default)
I receive an empty output below?
val tt : unit = ()
Any ideas why?
I think the Fourier.BluesteinForward method stores the results in the input array (by overwriting whatever was there originally).
If you do not need the input after running the transform, you can just use x and read the results (this saves some memory copying, which is why Math.NET does that by default). Otherwise, you can clone the array and wrap it in a more functional style code like this:
let bluesteinForward input =
let output = Array.copy input
MathNet.Numerics.IntegralTransforms.Fourier.BluesteinForward
(output, FourierOptions.Default)
output
So if you go to a bank there is a device from which you can pull a number out.
I want to write a function like that. So everytime this function is called we get a next number in the series.
So if this function is called first time, we get 1. second time we get 2.... so on and so forth.
this is what I have written so far
let X =
let myseq = seq {1 .. 100}
let GetValue =
Seq.head (Seq.take 1 myseq)
GetValue;;
let p = X;;
p;;
p;;
p;;
But it always return 1. My hope was that since the sequence is a closure, everytime I do a take, I will get the next number.
I also tried this
let X =
let mutable i = 1
let GetValue =
i <- i + 1
i
GetValue;;
let p = X;;
p;;
p;;
p;;
This one only prints 2...
You have to return a function. And to it, you have to pass something every time, i.e. your +1 has to be deferred.
let factory =
let counter = ref 0
fun () ->
counter.Value <- !counter + 1
!counter
and now you get
> factory();;
val it : int = 1
> factory();;
val it : int = 2
doing it this way has the nice side-effect, that you completely hide the mutable reference cell inside the function and thus there is no way to somehow tamper with your counter.
Just for a reference, if you wanted a version that uses sequences (just like the first approach in your question), you can do that using the IEnumerable interface:
let factory =
// Infinite sequence of numbers & get enumerator
let numbers = Seq.initInfinite id
let en = numbers.GetEnumerator()
fun () ->
// Move to the next number and return it
en.MoveNext() |> ignore
en.Current
It behaves the same way as factory in Daniel's answer. This still uses mutable state - but it is hidden inside the enumerator (which keeps the current state of the sequence between MoveNext calls).
In this simple case, I'd use Daniel's version, but the above might be handy if you want to iterate over something else than just increasing numbers.
You need to move the variable outside the declaration. You also need to declare a function so that it gets evaluated each time it is called.
let mutable i = 1
let X() =
i <- i + 1
i
This ensures that the function is called each time and that the variable is correctly incremented.
I'm attempting to learn myself up on F#, and I fear I'm not understanding something as well as I should.
I'm trying to recreate the functionality of a book I rather like (Creative Cursing from Royal and Panarese).
In a nutshell, you have two separate wordlists from which two random words can be chosen, resulting in an odd phrase. Simple enough?
Here's what I have:
#light
open System
open System.IO
let getWordList file =
File.ReadAllLines( file )
let getRandArrElement (arr : string[]) =
let rnd = Random( 0 )
arr |> Seq.nth (rnd.Next arr.Length)
let wordList1 = getWordList "words1.txt"
let wordList2 = getWordList "words2.txt"
let word1 = getRandArrElement wordList1
let word2 = getRandArrElement wordList2
printf "%s %s" word1 word2
It works, too. With the exception that it returns the same phrase every time it's run.
I have a feeling that what it's doing is calculating one random value per call to "getRandArrElement" at compile time, then using that value as THE value (which I think is weird, but what do I know?).
Whats wrong with my logic, and how do I fix it?
Your problem is here:
let getRandArrElement (arr : string[]) =
let rnd = Random( 0 )
arr |> Seq.nth (rnd.Next arr.Length
Random numbers aren't really truly random. They take a seed value, compute a random number between 0.0 and 1.0; that new value is used as the next seed. In other words, Random i spurely deterministic, so seeding with the same value over and over yields the same output sequence.
And since you're always constructor a new Random with the same seed, you're getting the same random number as output everytime.
I suggest a few improvements:
use let rnd = Random(). The default constructor uses the system clock as a seed, so that you'll get a different sequence. (Its still possible to get the same sequence. The system clock has a resolution of about 10 ms, so construction two Randoms in that interval will result, with high probability, of being seeded with the same value.
If you use let rnd = Random(0), even if rnd is outside your function, you'll get the same sentences in the exact same order everytime your run your program.
You can move the declaration of rnd outside your function so you're not constructing it over and over. As an alternative, you can write this:
let getRandArrElement =
let rnd = Random()
fun (arr : string[]) -> ...
F# executes all parameterless values when you open a module, so rnd will be assigned right away, and getRandArrElement is assigned the value of fun (arr : string[]) -> ....
Use arr.[index] instead of arr |> Seq.nth (rnd.Next arr.Length). Its not only more concise, but its also O(1). Seq.nth treats it like a sequence, it walks one element at a time until it gets to the element matching the given index, making the operation O(n).
The final result should be something like:
let getRandArrElement =
let rnd = Random()
fun (arr : string[]) -> arr.[rnd.Next(arr.Length)]
You are using a new Random with the same seed every time, this is expected behavior - if the same seed is used repeatedly, the same series of numbers is generated. I would suggest you move the declaration of rnd out of the function, that will solve your problem:
let rnd = Random();
let getRandArrElement (arr : string[]) =
arr |> Seq.nth (rnd.Next arr.Length)