在F#代码中省略bind()参数的unit参数是否会产生差异?
input()改为input的影响 Great question—let's break this down step by step using your code from the F# Programming Wiki Book's computation expressions chapter.
First, let's clarify the type of the value returned by createMsg:
let createMsg msg = fun () -> printf "%s" msg; System.Console.ReadLine()
createMsg takes a string message and returns a function of type unit -> string. This means you have to call this function (with ()) to actually trigger the prompt and read user input—until you call it, nothing happens, and you just hold a reference to the function itself.
Now look at the original bind function:
let bind(input, rest) = match System.Int32.TryParse(input()) with | (true, n) when n >= 0 && n <= 100 -> rest(n) | _ -> None
Here, input is that unit -> string function. Using input() calls the function, executes the prompt/input logic, and returns a string—which is exactly what System.Int32.TryParse expects (it takes a string as input).
What happens if you change input() to input?
If you modify the line to:
match System.Int32.TryParse(input) with
You'll get a compiler error immediately. Why? Because input is a unit -> string function, but System.Int32.TryParse requires a string argument. The types don't match—F# won't let you pass a function where a string is expected.
Beyond the compile error, even if you tried to force it (which you can't), the logic would break entirely: you're no longer executing the input-reading code, you're trying to parse the function itself as an integer, which makes no practical sense.
Key Takeaway
The () isn't just a "unit parameter" to skip—it's how you invoke the function returned by createMsg. Without it, you're working with the function reference instead of its output, which is a critical type and behavioral difference.
内容的提问来源于stack exchange,提问作者Ashok Bhaskar

