I wanted to talk about templating, since templating is a common thing you run into. Often times you want to cleanly do a string replace on a bunch of text, and sometimes even need minimal language processing to do what you want. For example, Java has a templating engine called Velocity, but lots of languages have libraries that do this kind of work. I thought it’d be fun to create a small templating engine from scratch with F# as an after work exercise.
The goal is to give the templating processor a set of lookup bags that can be resolved by variables. For example, if I use a variable
$devshorts.isgreat that should correspond to a bag that is keyed first off of
devshorts which returns a new bag, and then a new bag that has a key
isgreat which should return a value.
Getting the AST
First, lets parse the … Read more
In a few recent posts I talked about playing with fparsec to parse data into usable syntax trees. But, even after all the time spent fiddling with it, I really didn’t fully understand how combinators actually worked. With that in mind, I decided to build a version of fparsec from scratch. What better way to understand something than to build it yourself? I had one personal stipulation, and that was to not look at the fparsec source. To be fair, I cheated with one function (the very first one) so I kind of cheated a lot, but I didn’t peek at anything else, promise.
The principle behind combinators is that they are a way to take two functions and combine them into another function. Functional programming is chock full of this pattern. In general, you can combine any function to get any other function, but what makes a combinator … Read more
Since I was playing with fparsec last week, I decided to redo (or mostly) the parser for my homebrew language that I’ve previously posted about. Using fparsec made the parser surprisingly succinct and expressive. In fact I was able to do most of this in an afternoon, which is impressive considering my last C# attempt took 2 weeks to hammer out.
As always, it starts with the data
type Op =
type Ast =
| Statement of Ast
| Expression of Ex
| Function of string option * Argument list option * Ast
| Scope of Ast list option
| Class of Ex * Ast
| Conditional of Ex * Ast * Ast option
| WhileLoop of Ex * Ast
| ForLoop of Ast * Ex * Ex * Ast
| Call of string * Argument
… Read more