How To Define Function In Elm

TL;DR

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 with space.
  • = separates function signature from the body
  • right from = is a set of expressions (body). The meat part of the function. We multiply price with 0.25 float because the Croatian VAT tax is 25%

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

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

A 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

--

--

Founder of Tentamen, software testing agency.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store