Functions Tutorial, Part 4¶
You can download the source code for this tutorial here.
Ludwig allows you to set local variables through the
You can do so in a binding or in a function. The line after the
keyword must have the same indentation. Let’s demonstrate the
keyword in a binding, first.
myBinding: let x: 1 x + 2
Here, the binding
myBinding will be bound to the value
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
if the remainder is 1, it returns a Boolean value of
fun isOdd(n: Int) -> Bool: let x: 2 n % x == 1
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,
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: