So, if you want to write out a line to the console in F#, you do the following:
System.Console.WriteLine "foo"
Originally I thought the following was pretty much identical, just more verbose, but actually it gives the error "A unique overload for method 'WriteLine' could not be determined based on type information prior to this program point":
(fun line -> System.Console.WriteLine line) "foo"
It seems the second version is confused by the presence of overloaded WriteLine methods that take a string as well as other arguments. Is my assumption along the right lines?
What Are Anonymous Functions? An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle. Anonymous functions can accept multiple inputs and return one output.
However, an anonymous function returns only one output. If the expression in the function returns multiple outputs, then you can request them when you invoke the function handle. For example, the ndgrid function can return as many outputs as the number of input vectors. This anonymous function that calls ndgrid returns only one output (mygrid).
As JavaScript supports Higher-Order Functions, we can also pass anonymous functions as parameters into another function. Example 3: In this example, we pass an anonymous function as a callback function to the setTimeout () method. This executes this anonymous function 2000ms later. console.log ("Welcome to GeeksforGeeks!");
For example, you’ll commonly use anonymous function as arguments to other functions. In base R, the syntax for creating an anonymous function is very similar to the syntax for a named function. The only difference is that you don’t assign the function to a variable. The following is the anonymous function version of excited_word ().
Not exactly. In the first case, the function call knows that it's being applied to a string literal, so it can do overload resolution to find the string overload.
In the second case, line
is an unsolved type variable to type inference at the point of the call to the overloaded WriteLine
method, so it doesn't know which overload to pick, and it hasn't seen the string argument yet, as type inference is left-to-right.
Change it to
"foo" |> (fun line -> System.Console.WriteLine line)
and it will work, because the type inference variable for line
will get unified with string
from "foo" coming in, before it needs to determine the WriteLine
call.
So they key is left-to-right type inference; in the absence of a solution to a type variable, it may not be possible to pick an overload yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With