TL;DR
Let’s create our first Elm function that lives in a module. This post is part of the functional language series.
Our task is to create function that will calculate Croatian VAT value based on a product price. In the above image, you can see what you need to type in your favorite editor:
cro
is the function name. The same rules are applied as for the Elm module.price
It is the first parameter. If you need more, separate parameters withspace
.=
separates function signature from the body- right from
=
is a set of expressions (body). The meat part of the function. We multiply price with0.25
float because the Croatian VAT tax is25%
Let’s put our first Elm function through our processor:
Remember that we need first to compile the Elm file into the Javascript code. We run it in
elm repl.
Let’s make some errors
If you do not start function definition at first column:
The note has a meaningful error message. It says, “when something,” because it is tough to write a program that would identify programming constructs. But we know that we tried to define a function, so “when something” is in our case cro
function.
Let’s make some runtime errors (do not forget to edit cro function and recompile it):
When you run function without a parameter, you get function signature printout: <function> : Float -> Float
That means that Vat.cro
is a function where the input parameter is of type Float
and the return value is also Float
. If you would have more input parameters, let’s say two, the signature would be: <function> : Float -> Float -> Float
Wrong parameter type triggered an error. The explanation is pretty good. We even got a hint on how to resolve our error. This is possible because, after the compilation, the program has more specific information about your function. In compile-time, it only has free text.
Remember. Do not be mad at the programming language author. Writing compilers is really hard.
Remember What You Learned
- how to define a function with parameters
- function return value
- no parentheses
- no return keyword, expression-oriented language
- how to call a function
- whitespaces as separation
- function signature using
->
- error messages