Skip to main content
Logo image

Problem Solving with Algorithms and Data Structures using Kotlin The Interactive Edition

Section 1.14 Defining Methods

The earlier example of procedural abstraction called upon a Kotlin function called sqrt from the kotlin.math module to compute the square root. In general, we can hide the details of any computation by defining a function. A function definition requires a name, a group of parameters, and a body. It may also explicitly return a value. For example, the method defined below returns the square of the value you pass into it.
fun square(n: Double): Double {
    return n * n
}

fun main() {
    println(square(3.0))
    println(square(square(3.0)))
}
9.0
81.0
Let’s look at the first line of the method one token at a time:
  • fun says that this is defining a function.
  • square is the name of the function.
  • (n: Double) specifies the type and name of the function’s parameter(s); in this example there is only one parameter. This means that square needs only one piece of data to do its work.
  • : Double is the type of data this function will return.
The details of how the function works are hidden “inside the box”; it returns the result of multiplying result of n * n.
We can invoke or call the function by giving its name and passing an actual parameter value, in this case, 3.0 to fill in the parameter. Note that the call to square returns a Double that can in turn be passed to another function invocation.
We could implement our own square root function by using a well-known technique called Newton’s method or the Newton–Raphson method, named after Isaac Newton and Joseph Raphson. The Newton–Raphson method for approximating square roots performs an iterative computation that converges on the correct value. The equation \(newguess = \frac {1}{2} * (oldguess + \frac {n}{oldguess})\) takes a value \(n\) and repeatedly guesses the square root by making each \(newguess\) the \(oldguess\) in the subsequent iteration. The initial guess used here is \(\frac {n}{2}\text{.}\) Listing 1.14.1 shows a program with a function definition that accepts a value \(n\) and returns the square root of \(n\) after making 20 guesses. Again, the details of the Newton–Raphson method are hidden inside the function definition and the user does not have to know anything about the implementation to use the method for its intended purpose. Listing 1.14.1 also shows the use of the // characters as a comment marker. Any characters that follow the // on a line are ignored.
Listing 1.14.1. Newton-Raphson method for approximating square toots.

Exercises Exercises

1. Self Check.

Here’s a self check that really covers everything so far. You may have heard of the infinite monkey theorem? The theorem states that a monkey hitting keys at random on a typewriter keyboard for an infinite amount of time will almost surely type a given text, such as the complete works of William Shakespeare. Well, suppose we replace a monkey with a Kotlin function. How long do you think it would take for a Kotlin function to generate just one sentence of Shakespeare? The sentence we’ll shoot for is: “methinks it is like a weasel”.
The way we’ll simulate this is to write a function that generates a string that is 28 characters long by choosing random letters from the 26 letters in the alphabet plus the space. We’ll write another function that will score each generated string by comparing the randomly generated string to the goal.
A third function will repeatedly call generate and score, then if 100% of the letters are correct we are done. If the letters are not correct then we will generate a whole new string. To make it easier to follow your program’s progress this third function should print out the best string generated so far and its score every 1000 tries.
In order to do this program, you will need to know how to generate random numbers. The following program generates ten random numbers in the range 0 up to (but not including) 100:
Line 1 imports the Random class from the kotlin.random package.
Lines 4-7 produce the random numbers by calling the Random class nextInt method. The argument is the exclusive upper bound on the random integer; thus, this statement will generate a number from 0 (inclusive) up to, but not including, 100 (exclusive).
Though you do not need it for this program, for the sake of completeness: If you need to generate a double, call the nextDouble() method, which returns a double value from 0.0 (inclusive) up to, but not including, 1.00 (exclusive).

2. Self Check Challenge.

See if you can improve upon the program in the self check by keeping letters that are correct and only modifying one character in the best string so far. This is a type of algorithm in the class of ‘hill climbing’ algorithms, that is we only keep the result if it is better than the previous one.
You have attempted of activities on this page.