Signature

From void to unit

Issues with void in Cβ™―

void needs to be handle separately = 2 times more work 😠

  • 2 types of delegates: Action vs Func<T>

  • 2 types od task: Task vs Task<T>

Example : ITelemetry

interface 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

πŸ’‘ What about creating a Void type, a singleton with no data in it:

Let's play with it...

ITelemetry simplification

First, 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

In 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 void functions, we have functions returning the unit type. (1)

  • Rather than functions with 0 parameter, we have functions taking a unit parameter that can only be (). (2)

ignore function

Remember : 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 -> TResult

  • 3-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?