Signature
From void to unit
Issues with void in Cβ―
void in Cβ―void needs to be handle separately = 2 times more work π
2 types of delegates:
ActionvsFunc<T>2 types od task:
TaskvsTask<T>
Example : ITelemetry
ITelemetryinterface ITelemetry
{
void Run(Action action);
T Run<T>(Func<T> func);
Task RunAsync(Func<Task> asyncAction);
Task<T> RunAsync<T>(Func<Task<T>> asyncFunc);
}π Mads Torgersen is the C#'s Lead Designer. In his interview by Nick Chapsas, at 1:21:25, he indicates the 3 features he would completely remove from C#: event, delegate and void!
Type Void
The issue with the void is that it's neither a type nor a value.
π‘ What about creating a Void type, a singleton with no data in it:
Let's play with it...
ITelemetry simplification
ITelemetry simplificationFirst, let's define the following helpers to convert to Void:
Then, we can write a default implementation (Cβ― 8) for 2 of 4 methods:
Type unit
unitIn Fβ― theVoid type exists! It's called unit because it has only one instance, written() and that we use like any other literal.
Impact on the function signature
Rather than
voidfunctions, we have functions returning theunittype. (1)Rather than functions with 0 parameter, we have functions taking a unit parameter that can only be
(). (2)
ignore function
ignore functionRemember : in Fβ―, everything is an expression.
β No value is ignored, except ()/unit designed for this purpose
β At the beginning of an expression or between several let bindings, we can insert unit expressions worth ()/unit, for example printf "mon message"
Issue: we call a function which triggers a side-effect but also returns a value we are not interested in.
Example:
save is a function that saves to the database and returns true or false
Solution 1 : discard the returned value
Solution 2 : use the built-in ignore function, that has this signature :'a -> unit
β Whatever the value supplied as parameter, it ignores it and returns ().
Other examples:
β οΈ Trap: ignoring a value that we should use in our program.
Arrow notation
0-parameters function:
unit -> TResult.1-parameter function:
T -> TResult.2-parameters function:
T1 -> T2 -> TResult* 3-parameter function: `T1 -> T2 -> T3 -> TResult3-parameters function:
T1 -> T2 -> T3 -> TResult
β Quiz
Do you know why we have
->between the parameters? What is the underlying concept?
Answer in the next page...
Last updated
Was this helpful?