Monotonic Array
Task
You are given an array of integers. Write a script to find out if the given array is Monotonic. Print 1 if it is otherwise 0.
An array is Monotonic if it is either monotone increasing or decreasing.
Solution
|
|
Discussion
I prefer a functional approach so we create a list of Rakus Order Types:
|
|
For this we combine the zip operator as a metaoperator by combining it with the comparison operator. The first example creates the following list:
|
|
Now we have to check that the list does not contain a More
and a Less
element. I created the is-monotonic
function which does this using quite a few
of Raku’s features:
|
|
On the one hand we use the fact that the last statement is automatically used as
a return value so we can leave out the return
keyword. Next is the
ternary operator. As we only return
a boolean value depending on one condition, it keeps the code compact but still
clear. The condition makes use of the any
to create a junction. This way we don’t
have to iterate the list manually checking each element.
|
|