Full source codeNext chapter

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

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

type Parenthesis = Unit `S` 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 = by example
 `yokl` Forth `ha` Run `ha__` deposit `la` analyze `he'he'hv___` by `hv` Empty @List
 `yok_` Check `ha` remnant `ha'he` that @(List Unit)
 `yi__` Error `hu` "[ERROR] We missed some bracket, oh my!" `ho` is @(List ASCII)
   `la` Valid `hu` "[VALID] Everything is seem to be good."
 `yokl` Forth `ha` Run `ha` output

Next time we will introduce different types of brackets.