Red Parse: simple rules

In the last post, I introduced a very simple find-and-replace in parse.

Let’s refactor this a bit to set some rules and in doing so, make this code more readable.

So we had this:

s: "this is a fantastic day"
parse s [to "fantastic" change "fantastic" "great"]

which replaces one instance of “fantastic” with “great”.

We could break down the rules above into:

key-word: "fantastic"
my-find: [to key-word]
my-replace: [change key-word "great"]
parse s [my-find my-replace]

This will help make the parse part a little more readable or understandable.

When run in the REPL, this will result in s being updated to:

s
== "this is a great day"

The readability comes about by creating rules for my-find and for my-replace. Each rule is placed in square brackets or a block. Without the brackets, you’d get an error.

Because parse evaluates rules from left to right, the first rule my-find is evaluated first, and if successfully evaluated, then parse moves onto my-replace.

It’s possible to make the code perhaps a little more elegant by:

do-this-action: [my-find my-replace]

and then parse becomes:

parse s do-this-action

You get the idea.

This concept of setting up granular rules will greatly help maintain clarity and maintainability as you write your own parsing routines.

One thought on “Red Parse: simple rules

Leave a Reply

Your email address will not be published. Required fields are marked *