Functions Tutorial, Part 4

You can download the source code for this tutorial here.

Local Variables

Ludwig allows you to set local variables through the let keyword. You can do so in a binding or in a function. The line after the let keyword must have the same indentation. Let’s demonstrate the let keyword in a binding, first.

myBinding: let x: 1
           x + 2

Here, the binding myBinding will be bound to the value 3.

Now, let’s look at using local variables in a function. Remember the function in Functions Tutorial, Part 1? Here it is:

fun isOdd(n: Int) -> Bool:
  n % 2 == 1

We’re going to use the let keyword to locally bind x to the value 2. This accomplishes the same thing the original function does – it determines if a number is odd by dividing it by x, or 2, and if the remainder is 1, it returns a Boolean value of true.

fun isOdd(n: Int) -> Bool:
  let x: 2
  n % x == 1

Exercise 4

Ready for your next exercise? Below is a function, but there’s something wrong with it. Find the mistake and fix it, so that the module compiles.

When fixed, the multiplyNumber function takes an integer, multiplies it by the value designated by the let keyword (in this case, 3), and returns the product as an integer.

fun multiplyNumber(n: Int) -> Int:
  let x: 3
 n * x

Hint: If you try to compile the module as is, the compiler will give you a tip about what’s wrong.

You can download the file here. Compile it by executing the following:

lwc FunctionTutorial4.lw