Solution Review: Absolute Value
Explore how to create a Scala function that calculates the absolute value of a number. Understand checking conditions for positive or negative inputs and returning the correct value. This lesson helps you apply function basics critical for effective Scala programming.
Task
In this challenge, you had to create a function which computes the absolute value of a given number.
Solution
A skeleton of the function was already provided for you. Let’s look it over.
def absolute(x: Double): Double = {
}
The function name is absolute, and it takes a single parameter of type Double and returns a value of type Double.
The parameter name is x and is the number whose absolute value needs to be calculated. The absolute value of a number is simply the positive value of the number after ignoring its signs (+ or -). Hence, if the given number is x, we first need to check if it is positive or negative. If it is negative, we will return its positive value by multiplying the number with -.
-(x) or -x
If the number is positive, we will simply return it as is.
x
You can find the complete solution below:
You were required to write the code on line 2.
In the next lesson, we will go over the different evaluation strategies with which an expression is evaluated.