Matthew Walton’s Blog

Sunday, 7th March 2010

Pork and Apple Burgers (a recipe)

Filed under: Food,Recipe — Matt Walton @ 19:17

Usually I make beef burgers, but I fancied a change, and this worked out so well with a bit of experimentation and some inspiration from various recipes online that I thought I’d post it. There’s probably an identical recipe somewhere else – I can’t be the only person who’s come up with this. Ah well.

  • about one pound of minced pork
  • a third of a Bramley apple
  • one small onion
  • freshly ground black pepper
  • Worcestershire sauce
  • some buns in which to place the burgers for eating

First things first: peel and chop the onion into small pieces, then fry it in olive oil until soft. When it’s nearly ready, peel the third of the apple and grate it through a coarse grater into the onion pan. Stir this all in and cook gently on a low heat.

At this point you probably want to do something with the rest of the apple before it goes brown. I made pudding with mine.

Once the apple’s cooked a little and the whole onion/apple mixture is nice and soft, stir in a generous couple of dashes of Worcestershire sauce and a tasteful grind of black pepper. Dump this in a bowl with the pork mince and mix it all together well. Divide into four equal parts and form into balls.

Heat a heavy-based frying pan until it’s really hot, then add a little ground nut or vegetable oil. Tip the pan to coat all over with oil, then pop two burger balls in and smash them flat with a suitably-shaped implement (say… a fish slice, although if it’s got holes or slits in it, careful as the mixture will want to ooze through them and get stuck). There will be lots of sizzling and steam and some smoke, and you might want to be careful of the smoke alarm at this point. Mine usually goes off when I do burgers. Fortunately I don’t live in a big building with a proper fire alarm system…

After a minute or so, flip the burgers. Keep an eye on them, and flip again whenever seems necessary until they’re just cooked through. Put them on a plate and keep warm while you repeat the procedure with the other two burgers.

In case you’re wondering, yes this is how the infamous smash and scrape method of burger cookery works out for me. My frying pan is almost relentlessly nonstick, so there really isn’t much scraping going on, but I can cope with that. It won’t form a crust like beef burgers do, but that’s okay. Trust me.

Serve in buns, with plates because they’ll drip delicious juices.

Wednesday, 2nd December 2009

Translating Python

Filed under: Perl 6 — Matt Walton @ 23:08

@paulrpotts tweeted about a blog entry explaining why the founder of a company chose Common Lisp for a web project. There were good reasons given for not using Python, which Paul agrees with, and Paul linked to a blog entry about some of his own experience in Python. In that is a bit of Python code, and I started thinking what it would look like in Perl 6.

The code relies on an XML node class, which is presumably one that you can find in Python’s library. Perl 6′s library is rather sparse right now, so I’m going to partially specify a Node class which is basically the same as the bits of it used by Paul’s Python code, just with some Perl 6-ish naming conventions.

class Node {
  enum NodeType <TextNode>;
  has $.data;
  has Node @.child-nodes;
  has NodeType $.node-type;
  method get-elements-by-tag-name(Str $name) { ... }
}

This, then, is a more or less direct translation of Paul’s Python code into Perl 6. The main difference is that Perl 6 has type annotations, we don’t have to import anything to get partial function application (that’s given by .assuming) and we don’t have to do any tricks to get string reduction, because of Perl 6′s [] metaoperator.

# Given a list of nodes, return the .data member of all nodes
# which have node-type of TextNode
sub get-text-data(Node @nodelist) {
    @nodelist.grep: { .node-type ~~ Node::TextNode }.map: { .data }
}

# Given a list of nodes, extract the text data and return it as
# one long string
sub extract-text(Node @nodelist) {
    [~] get-text-data(@nodelist);
}

# Given a node tree and an element name, find the first text
# element of that name and get the text from all its child nodes
sub get-one-text-element(Node $node, Str $name) {
    my @elements = $node.get-elements-by-tag-name($name);
    @elements.elems == 1 or die;
    extract-text(@elements[0].child-nodes);
}

# Given a node tree and a list of element names, extract all the
# text from each named node and return as a hash of name => text
sub make-text-element-dict(Node $node, Str @namelist) {
    return @namelist Z @namelist.map(
      &get-one-text-element.assuming(node => $node)
    );
}

This could of course be shorter – most of these subs don’t need to be defined here, we could turn it into a very few lines indeed, but I’m assuming that the subs might be needed elsewhere in the form presented here.

A few things to point out for Perl 6 novices:

As in Perl 5, variables starting with @ are arrays (if you want to get precise, it means there’s something in there which does the Positional role, so you can expect to be able to use [] element accessors and suchlike).

The [~] construct is actually two things – first, the infix operator ~, which in Perl 6 is string concatenation, surrounded by the [] metaoperator which turns it into a list reduction. Thus the effect is to concatenate all the list elements together and return one big string.

Perl 6 identifiers can have hyphens in them. The parser’s smart enough to distinguish between those and use of infix -.

Perl 6 subroutines can have formal parameter lists. These parameters, like Perl 6 variables, can have type information explicitly declared for strict checking.

You can pass blocks of code to methods like .map and .grep using :{} syntax, which saves some nested brackety things.

You can produce a curried version of a function using its .assuming method.

The infix operator Z works like the zip function in Python and Haskell.

I haven’t checked if this would compile, but I think it’s pretty close.

Thursday, 23rd July 2009

Planless testing in Perl 6

Filed under: Perl 6 — Matt Walton @ 11:50

In #perl6, our eyes were caught by a post on Matt Trout’s blog concerning the problems which arise from the traditional Perl way of test modules which require you to state at the start of your test file how many tests you’ll be running. I’m not going to repeat his arguments because they’re good ones. It didn’t take a great deal for people to agree that we should have a planless testing module for Rakudo.

Rakudo already ships with a fairly basic Test.pm which already had some support for planless testing, although you still had to explicitly tell it that’s what you wanted:

plan *;

Whereas we’d rather like it if you could just leave out the call to plan when you weren’t planning (hah!) to use a plan. We also decided to use the done_testing idea, so that you call this in planless mode after your tests are complete to mark explicitly that you’ve run as many as you wanted to.

I was able to put together a new version of Test.pm which contains all these enhancements for planless testing, while at the same time operating transparently in planned mode for all the test modules already out there. I for one didn’t want to go through the Perl 6 spectest suite and change all those…

The patch is submitted to RT, so hopefully it will land in Rakudo before too long (assuming nobody finds any screaming bugs in it). Then your test modules can look like this:

use Test;
use MyModule;

ok(MyModule::do-something(), "Doing something");

done_testing;

Monday, 23rd March 2009

Perl 6 Grammars and Action Methods

Filed under: Perl 6 — Matt Walton @ 15:43

I want to share some Perl 6 grammar knowledge and a bit of my enthusiasm for what this language is going to let people do. This is based on work I’ve been doing for the Form.pm module, which will be the replacement for Perl 5′s rather clunky format function.

Imagine that Christmas has come: you’re writing a programme in Perl 6 (you can actually do this today, it’s just that there are large chunks of the language which nobody has implemented yet). In your wonderful Perl 6 programme, your world domination plan includes the need to parse some text, so you reach for a grammar, the overpowered, mutant grandson of Perl 5′s regular expressions.

Grammars are really a special kind of class, containing a special kind of subroutine (being regexes, rules or tokens rather than subs, methods or submethods). Say your grammar looks like this:

grammar Statements {
  regex TOP {
    ( <statement> ';' )*
    {*}
  }
  regex statement {
      'hello' <ws> <string> {*} #= hello
    | 'goodbye' <ws> <string> {*} #= goodbye
  }
  regex string {
    '"' (.*?) '"'
    {*}
  }
}

That is, you’re going to match against zero or more statements, which are separated by semicolons and consist of either ‘hello’ followed by some whitespace and a double-quoted string, or ‘goodbye’ followed by some whitespace and a double-quoted string. I know the string regex is bad in that it’s awful at delimiter matching, but it’ll do for now in the interests of keeping down the complexity. Also, in real life you’d probably have rather more flexible rules for separating statements, but I’m showing off AST-building here, not fancy regexes.

So what does it all mean? The syntax isn’t too difficult to get your head around: an identifier inside angle brackets invokes another regex as a submatch. | delimits alternatives and * is the zero-or-more quantifier. {*} is where the clever bit comes in. When the matcher sees {*} in a rule, it knows that it should go and call a method with the same name as the current rule in an object which was passed to the matcher when it was invoked. These are called action methods, and offer a fantastic way to use the grammar system for building abstract syntax trees or other constructions which represent your parsed text. To make this even more useful, if the line with the {*} on it ends with a comment like those seen in the statement rule above, the text of the comment will be passed to the action method, so you can signal to it which alternative branch you want it to deal with.

Now in real life your action methods might produce one of several possible classes, maybe from a huge tree of classes which can represent your AST, or from a set of classes which use a common set of roles, or maybe you’re going down the route of some of the calculator examples which have been developed which do the calculations right there in the action methods, and represent nodes by their results which are just numbers. In this example, to avoid having to define a class for statements (which is really quite simple), I’m just going to produce a hash with two keys: verb and string.

So we write a class to hold the action methods. We can call it whatever we like, but the method names and the rule names they’re triggered by have to match.

class Actions {
  method TOP($/) {
    my @statements = gather for @( $/[0] ) -> $submatch {
      take $submatch<statement>.ast;
    }
    make @statements;
  }
  method statement($/, $key) {
    my %s;
    %s<verb> = $key;
    %s<string> = $/<string>;
    make %s;
  }
  method string($/) {
    make $/[0].ast;
  }
}

Now we see the real magic at work. First, each action method has a parameter $/, which is the default name for the match object. Calling it $/ lets you call make without any special considerations because the background match object is just there. A match object, by the way, is what a regex returns when it matches something, and it contains all the information about where and what it matched, including other match objects for subpattern matches.

Next, we see that the statement method has a second parameter, $key – this is where the comment-syntax key strings arrive. It’s entirely optional, so I only put it on the method that would actually get some use from it.

The make function is really key to this business – it alters the match object to provide a different result. The match object itself stays intact, but it has a slot (accessed through the .ast method) which can carry any object you like which represents the matched text. It’s called .ast because of its frequent use in building abstract syntax trees, and here it’s going to carry our hashes.

Let’s look at each method in turn. The action method for string is straightforward. If you look back at the regex for string, you’ll see that it has a captured subpattern between the double-quote delimiters. Subpatterns like this appear in the Match object as array elements, so you can use the array indexing operator to access them. We know here that there will only be one, and as it’s an array it’ll be in slot 0, so we can just say $/[0]. We call .ast on it, because the default result is a string representing what was parsed by that pattern. In this case that’s exactly what we want, so we set it to our result and we’re done.

Next, the statement method is a little more complicated. It creates a new hash, then sets the verb to the passed-in $key. Because string was invoked as a named subpattern, it can be found as a hash element of the match object, so we retreive $/<string>.ast, which will be the string that was produced by the string action method, and store that in the hash before using make to set it in our ast slot.

Finally, TOP has to deal with a list of subpattern captures. Because there’s a repetition quantifier on the capture, $/[0] will be an array. We can iterate over that with a for loop to get at the match object for each repetition, and then use the hash access to retrieve the match object for the statement subrule – which is of course the hash made by the statement action method.

In this case, we use gather for to construct the list lazily (or at least, it will be lazy once Rakudo has lazy lists). gather needs a loop construct, and within that construct you can call take as many times as you like – each time a new element will be added to the end of the list which is being constructed by the entire gather expression. Ultimately that list is assigned to @statements, and we make that as the final result from the match. In this case we take the ast slot from the submatch, but you may notice that there’s a backslash before its $. Why is this? Perl 5 programmers are probably thinking ‘ah, he’s taking a reference so that he can make an array of hashes’, and they’d be sort of right. Without that, the hash wants to flatten into the array, which is not what we want, so we use @\@ which in Perl 6 creates a capture (an astonishing Perl 6 construct which is used for everything from stopping things flattening into lists to passing subroutine parameters around), which in this case will just prevent the hash from flattening into the array. There may be a more elegant way to do this by ensuring that the hash isn’t taken in a context that’s going to cause flattening, but I haven’t figured that part out yet. In any case, the end result is an array of hashes, which is exactly what we want. The captures are entirely transparent to everything that tries to use it.

How do you run this? Very easily:

my $actions = Actions.new;
my $result = Statements.parsefile('somefilename', :action($actions));
for $result.ast -> $statement {
  given $statement<verb> {
    when 'hello' { say "Hello, $statement<string>"; }
    when 'goodbye' { say "Goodbye, $statement<string>"; }
  }
}

And that, as they say, is that, except that you can do all this in Rakudo Perl 6 today.

Sunday, 4th January 2009

A Pork Casserole

Filed under: Recipe — Matt Walton @ 15:20

This is really simple. I just finished eating a bowlful and it’s utterly gorgeous. I’m very vague on quantities.

Take about eight slices of streaky pork and cut into chunks. Chop a red onion and fry it in olive oil, then add two cloves of garlic, grated or crushed. Add six tomatoes cut into eighths, then the pork and stir well. Add herbs: perhaps sage and rosemary. A squirt of tomato purée, a dash of concentrated chicken stock, some hot water and some pearl barley (I have no idea how much I added – it just seemed like enough). Season with salt and pepper.

Simmer gently until the barley is soft and cooked through, then ladle into a bowl and enjoy with freshly baked bread, or by itself.

The rest will freeze nicely, or feed other people.

No picture; I’m too lazy today.

Powered by WordPress