For a given sequence of brackets we should check if those are balanced.

A bracket could be either opened - ( or closed - ):

type Parenthesis = Unit `ML` Unit

For this program we need to use effects:

  • State for storing a List of opened brackets.
  • Halts to stop and indicate a case of imbalance.

When we meet an opened bracket the only thing we can do is to put it atop of the stack:

deposit bracket = enter @(State `WR` List _ `JNT` Halts)
 `yuk__` New `ha` State `ha` Event `hv` push @List bracket

When we meet an closed bracket we check if at least an opened one previously has been added to the stack - if there is none, we should throw an error:

analyze _______ = enter @(State `WR` List _ `JNT` Halts)
 `yuk__` New `ha` State `ha` Event `hv` pop @List
 `yok__` Try `ha__` None `hu` it Error `la` Some `hu` it Valid

So far we are able to catch only one type of error - missing opened bracket. To catch another one, we need to wait until we finish traversing a sequence of brackets and check for leftovers in the stack - in this case there are missing closed brackets.

remnant = Empty @List `hu` it Valid
 `la` Nonempty @List `he'hu` it Error

We are ready to put everything together now:

main = Nonempty @List @Parenthesis
 `ha` Item (Opened Unit) `ha` Maybe `ha` Next
 `ha` Item (Closed Unit) `ha` Maybe `hv` Last
 `yokl` Run `ho` Forth `ha__` deposit `la` analyze
 `he'he'hv___` Empty @List Unit
 `yok_` Try `ha` remnant `ha'he` that @(List Unit)
 `yi__` is @(List ASCII)
   `hv` "[ERROR] We missed some bracket, oh my!"
   `lv` "[VALID] Everything is seem to be good."
 `yokl` Run `ho` Forth `ha` output

Full source code is available here.

Next time we will introduce different types of brackets.

Continue this tutorial