Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elm what is "x" in a type signature?

Tags:

elm

Trying to figure out how to get the current time, and I found the method, but don't know how to read the type signature.

The signature is now : Task x Time you can see it here.

Can't figure out how to search for it since they use x as a variable name everywhere, I can generally find the rightish place within the parser code, but have a lot of difficulty following it.

like image 698
Joshua Cheek Avatar asked Jun 16 '16 06:06

Joshua Cheek


2 Answers

The type x is a so called type parameter. This means that the type is not defined yet.

In your particular case, the definition of the type Task, the first type after Task denotes the type with which your asynchronous operation may fail.

At the moment of the definition of the function this type is not fully defined. You have the freedom, in your program, to use as error type the type you want

like image 109
marcosh Avatar answered Nov 17 '22 12:11

marcosh


The definition:

now : Task x Time

means (loosely translated):

Time.now is a Task which, when executed, will give you either:

  • output of type x if it fails,
  • output of type Time if it succeeds.

Since the Task Time.now can never fail, it doesn't matter what the error type is. In Elm, lowercase types (a, b, x, comparable, msg) mean that the type could be anything, i.e. the function would work with different types.

  • msg for message types.
  • comparable means that it needs to be a type where you can compare two values (e.g. if the function does comparison between to values of that type, to determine which one is larger etc).

This makes sense for input types. But less so for output. I guess in this case the x means more or less "not applicable". A Task type needs an error output type. But in this case, it is irrelevant.

Addendum: To actually get the current time, you would need to take two more steps:

  1. Performing the task, which returns a Cmd:
    timeCmd = Task.perform identity MyMsg Time.now
    This will perform the time-task, and wrap the resulting time in a Cmd MyMsg

  2. Handle the Cmd output: for this, you would need to include a MyMsg handler in your update function.

like image 40
wintvelt Avatar answered Nov 17 '22 12:11

wintvelt