Starting from Puppet 4, you can write functions in the Puppet language instead of Ruby. It is believed at some point that Puppet will move away from using Ruby in the backend, so any new functions you write should use the Puppet language if possible. The interesting thing about writing functions in the Puppet language is that there is no return statement; Puppet will return the last expression from a function as the return value. It is still possible to do more advanced programming while remaining within Puppet language. In the following example, we will use a rough estimation algorithm to calculate the square root of a number.
The first function is used to determine if we are close to the square root:
function close(Integer $number, Float $guess) {
if abs(($guess * $guess) - $number ) < 0.01 {
true
} else {
guessAgain($number,$guess)
}
}
This will either return true if $guess2 is within 0.01 of $number or it will use the next guessAgain function to return the next guess to the main function:
function guessAgain($number, $guess) {
($guess + ($number / $guess )) / 2.0
}
This function is used to make a correction to the current guess, to bring the estimation closer to the square root. The last function is where we do our recursion; recursion is where a function uses itself as part of the algorithm:
function sqrt_($number, $guess) {
if close($number,$guess) == true {
$guess
} else {
sqrt_($number, guessAgain($number, $guess))
}
}
In this function, if the close function returns true, we know we are close enough to the root and can return $guess to the calling function. If not, we call sqrt_ again with a new guess. The final function is just a wrapper of sqrt_ and is used so the caller need not set an initial guess:
function sqrt($number) {
sqrt_($number,1.0)
}
To see this in action, we'll need to call our sqrt function and use notify to print the values returned:
function sqrt_($number, $guess) {
if close($number,$guess) == true {
$guess
} else {
sqrt_($number, guessAgain($number, $guess))
}
}
Now when we run Puppet, we see the following output:
Notice: sqrt(4) = 2.000609756097561
Notice: sqrt(2) = 1.4166666666666665
Notice: sqrt(81) = 9.000011298790216