Skip to content

Numbers with equal rises and falls

editable example

Click the pencil to open this in an editor, change it, and run it in your browser. The same solution is posted on Rosetta Code.

ghul
use IO.Std.write_line
use Ghul.Pipes
balanced(n: int) -> bool => (
let rest mut = n
let balance mut = 0
while rest >= 10 do
let lower = rest % 10
let upper = rest / 10 % 10
if upper < lower then
balance = balance + 1
elif upper > lower then
balance = balance - 1
fi
rest = rest / 10
od
balance == 0
)
sequence() -> Pipe[int] => stream(1, n => n || n + 1) |> filter(balanced)
write_line("the first 200 numbers with equal rises and falls:")
let first_200 = sequence() |> take(200) |> collect_list()
for row in 0::19 do
write_line(
(0::9)
|> map(column => "{first_200[row * 10 + column],5}")
|> join(""))
od
let ten_millionth = sequence() |> skip(10000000 - 1) |> first()
write_line("the 10000000th is {ten_millionth}")