Flatten a list
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
union Nested is
ATOM(value: int)
LIST(items: Nested[])
si
use Nested.ATOM
use Nested.LIST
atom(value: int) -> Nested => ATOM(value)
list(items: Nested[]) -> Nested => LIST(items)
flatten(node: Nested) -> Pipe[int] is
case ►node
when (value): ATOM then
yield value
when (items): LIST then
for item in items do
yield in flatten(item)
od
esac
si
show(node: Nested) -> string =>
case ►node
when (value): ATOM then "{value}"
when (items): LIST then "[{items |> map(show) |> join(", ")}]"
esac
let input =
list([
list([atom(1)]),
atom(2),
list([list([atom(3), atom(4)]), atom(5)]),
list([list([list([])])]),
list([list([list([atom(6)])])]),
atom(7),
atom(8),
list([])
])
write_line(show(input))
write_line("[{flatten(input) |> join(", ")}]")
[[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] [1, 2, 3, 4, 5, 6, 7, 8]