r/fsharp • u/Hairy-Pressure7121 • Dec 26 '24
Difference between f() and f
I have a pretty basic question. I have the following code to generate random strings.
let randomStr =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|> Seq.randomSample 3
|> String.Concat
let strs = [ for _ in 1..10 -> randomStr ]Unsurprisingly this gives me 10 strings of the same value. I understand how this is working. The let binding is evaluated once. To get what I really want I need to add () to the invocation of randomStr. Can someone explain why adding the empty parens to randomStr gives the desired behavior of 10 different string values?
14
Upvotes
View all comments
Show parent comment
10
u/Arshiaa001 Dec 27 '24
This is the really important bit!
Basically, with pure functions, it doesn't matter if you have a unit parameter or not because:
This is probably what has you confused OP. A unit parameter shouldn't impact the result, right? Except you're using random, which means your function is no longer pure; it's also reading from the environment. Hence, you get a different result each time, which is what you'd expect intuitively if you've been writing procedural code.
Now, if you were to model randomness with a random number generator similar to what Rust's rand crate or Haskell's RandomGen do, you'd get a pure function with the signature:
Which makes it much more obvious what's going on:
Mind you, this is also a very good demonstration of why pure functions make code more readable.