Comments can be quite useful for:
- Providing documentation that explains how the code works.
- Preventing execution of some code when we are experimenting or trying to find the root cause of a bug.
Like most programming languages, Elm provides two types of comments: single line and multi-line.
Single Line Comments
Single line (also known as inline) comments start with --
. Elm will ignore any text between --
and the end of the line.
Multi-line Comments
Multi-line (also known as block) comments start with {-
and end with -}
. Elm will ignore any text between {-
and -}
.
Here is an example of a multi-line comment that explains how the not
function works in Elm.
Generally speaking it’s unnecessary to type comments in the repl. They are more appropriate for the code written in a file.
Toggling Comments
When we are experimenting with code, we often want to toggle comments. Most code editors provide a shortcut for toggling single line comments. For example, in Sublime Text and Visual Studio Code a comment can be toggled (on a Mac) by pressing Cmd
+ /
. However, these editors don’t have a good mechanism for toggling multi-line Elm comments. One handy trick we can use for that is to add and remove }
on the first line. Let’s say we have some code commented out like this:
Note: Your source editor may not know how to toggle even single-line Elm comments out-of-the-box. If that’s the case, you’ll have to install a plugin for that. Refer to the Source Code Editor section in Chapter 2 to find out how to install an Elm plugin for your favorite editor.
Notice we added extra -
after {-
and before -}
. Now to uncomment the code all we have to do is add }
to the end of the first line.
Because the leftover }
at the end is preceded by --
, Elm treats it as a single-line comment. To bring back the multi-line comment, just remove }
from the first line.