Forth DSL example

Forth is a language, like Lisp, that has a certain fascination for me. I’ve tried Forth a few times, but have always gone back to other languages. Recently I tried creating a Forth myself as a learning exercise: ultimc [1]. It compiles on Linux, Windows (theoretically), and under the Ultibo [2] unikernel for a bare metal Raspberry Pi Forth.

Creating my own Forth has taught me a lot about the language, and really made me understand the way it works. In this post, I am going to peer a little under the hood to show that Forth, like Lisp, has a secret sauce that you just don’t get with most other languages. Maybe it will excite you a little as to the unique possibilities of Forth.

Recently I came across some Forth code [3] that was as follows:


Notice how there’s a lot boilerplate code there: “0 constant:”, “1 constant:”, etc. Wouldn’t it be nice to write something like:


and have Forth “do the right thing”. Well, let’s see …

Here’s the code, written in gforth:
variable enum \ the current enumerated value, starting at 0
: enum++ enum @ dup 1+ enum ! ; \ increment enum, leaving the original enum value on the stack
: >enum nextname enum++ constant ; \ Given a name, set it to the value of enum as a constant
: enum1 parse-word dup if >enum 0 else 2drop 1 then ; \ scan the input buffer, and call >enum if legit
: enum: begin enum1 until ; \ keep going until the input buffer is exhausted

Just 5 lines of code, although admittedly it did take me a lot of time to figure out. The code needs a little elaboration.

PARSE-WORD and NEXTNAME act a little bit like CREATE, except that PARSE-WORD gets the next word from the input buffer, and NEXTNAME creates a word from the input buffer.

Now, if we’re at the end of the buffer PARSE-WORD returns a zero length string. This is what ENUM1 checks for. It only calls >ENUM if the string has at least 1 character. What it returns on the stack is the value 0 to signify success, and 1 to signify failure.

ENUM: then just loops around until the value 0 appears on the stack, implying that the input buffer is exhausted.

Let’s test it, using more condensed names:

enum: foo bar baz

And check our handiwork:

foo . bar . baz . \ outputs: 0 1 2

Can your language do that?


Posted in Uncategorized | Leave a comment

#FOOT I’m now bearish

I’m jaded, I admit it. I’ve seen enough wheels fall of the wagon that is AIM  to give newly-floated issues a second chance.

Brokers estimate 2.47p EPS for 2020. That gives is a forward PE of nearly 15. Investors are taking a gamble in the company, and I think that the current price is by far high enough for the risks they’re taking. Personally, this company is a bargepole stock.

Note that the projected EPS is below that for 2016.

I’m taking a look at the operating margins quoted on Stockopedia. Here they are: 2015: 0.6%
2016: 3,4%
2017: 5.8%
2018: 1.1%

They look like rubbish margins to me, and are basically 1/3 that for the specialty retail sector.

Stockopedia also rates the Earnings Manipulation Risk as High. That’s not always a reliable sign; I’m just throwing that out there. I should say, though, that the ROCE for the company was 3% in 2015, 20% for 2016, 124% for 2017, and 4% for 2018. So I wouldn’t put it past them that they’ve been screwing with the numbers.

What’s really convinced me, though, is the RNS put out yesterday that a PDMR bought £5000 worth of shares. These joke purchases after a substantial price fall are decidedly bearish, in my view.

I hear that the CEO is on maternity leave, too. Seeings as the company is circling the toilet at the moment, that’s poor form. And a little whiffy.

And, incidentally, I notice that the auditors are Grant “we’ll sign anything” Thornton.

Qualitatively, I’d say there’s too many red flags to this company. BWTFDIK.

I’ll follow up this company in maybe 6 months or a year’s time to see how it fared.

Stay safe out there.


Edit: “… AIM not to give …” changed to “…AIM to give…” Grr. I actually wrote is right the first time, but screwed up in the editing. Sorry about that.

Posted in Uncategorized | Leave a comment

Magic Hat Portfolio: RMG in, HVN out

Recruitment company HVN (Harvey Nash) leaves the portfolio by rotation, and more importantly, because it received a takeover offer last month. That caused the shares to shoot up to near the takeover price. There’s unlikely to be any upside from here, so it’s it’s just for the arbiters to play with. It has to be removed, whether I like it or not.

HVN has been in the portfolio for about two years, and has risen 98% since purchase. Now that’s the kind of return I like to see.

I had a look through Greenblatt’s Screen, and although there were some good candidates, I thought that there would be too much repetition of sectors. So I decided to try a variation: I created a Stockopedia Screen where the P/FCF (Price to Free Cashflow) was less than 10, and sorted the results by descending StockRank. I also wanted a yield at least 1.1 times that of the dividend yield of the market, and reasonable debt (PBT < net debt/3).

My criteria were a blend of ideas from Bruce Berkowitz, John Dorfman, and Robbie Burns. Berkowitz often said that he looked to buy companies on the P/FCF of less than 10 where he couldn’t kill the company. Dorfman has his “robot” where he buys companies on cheap PEs with debt less than equity. The Dorfman Robot has proven to be a considerable success. I have used dividend yield as a proxy for PE ratio. Dividends are real, though, and everyone loves them. Well, nobody hates them, let’s put it that way. Burns follows a simple rule that he requires debt to be under the limit I stated in the preceding paragraph.

RMG (Royal Mail) looked a reasonable candidate on that basis, so I chose that. We all know what RMG does, of course. I doubt it is going to shoot the lights out, but we’ll see how it goes. The vital stats on RMG are: P/FCF 8.2, yield 5.7% and StockRank of 97. It has a Quality score of 97, and a Value score of 91, so it is very much in keeping with the philosophy of Greenblatt.

I bought RMG for my own portfolio back in June 2018. It is down 7.8% since purchase, which is, of course, a little disappointing from my viewpoint.

As I noted on a Twitter post today, it was fairly easy to pick out candidates that were less than 10X FCF, had good divvies, and little debt: CTO, AIR, PSN, FXPO. Those ones really just off the top of my head.

IAG (Int’l Cons Airlines) – which owns British Airways – also fits the bill, depending on which data source you use. Stockopedia shows a P/FCF of 10.8, but I wonder if it’s mixing up Euro cashflows and GBP in market cap. I can’t quite reconcile it. Another source I had puts the the P/FCF as significantly less than 10. Stockopedia also puts it EV/EBITDA at 3.2. That is as cheap as chips, where you would expect something to go horribly wrong. But the trading outlook on 3 Aug was quite benign:

At current fuel prices and exchange rates, IAG still expects its operating profit for 2018 to show an increase year-on-year. Both passenger unit revenue and non-fuel unit costs are expected to improve at constant currency.

I also own shares in IAG, and I’m up 12% on these.

Another big company I noticed, but don’t own any shares in is BLT (BHP Billiton). Same deal: low P/FCF, reasonable debt, and fat yield. Everyone is nervous about commodities at the moment. It relates to perceptions about stalling Chinese growth, as I understand it.

I’ll stop the examples now. I think I’ve proven my point, which is this: it’s possible to find, fairly easily, even large companies that everybody knows about, trading at cheap valuations, with reasonable debt, offering some nice dividends.

I’ve heard a number of commentators say that they think that the current bull market is long in the tooth. But I’m finding stuff that’s worth investing in, so I’m actually fairly sanguine.

[Deleted pontifications about Brexit]


Posted in Uncategorized | Leave a comment

Oh no, I’m beginning to like perl5

I’ve been writing and rewriting my plain text accounting package in various languages for some time now. Incarnations have included bash/awk/sed, C, C++, Haskell, golang, Lisp, and Scheme.

I decided to try writing it in the vilest language of all: P5 (Perl 5). It’s 75 lines long. I expect the finished version will be no longer than 100 lines.

Here’s where I’m finding the strengths of Perl 5 to be:

  • Simple things are simple
  • It’s faster than Python
  • It’s near-ubiquitous.
  • It’s easy to pick up, despite the fact that I have rarely programmed in perl 5

Simple things are simple

Perl 5 seems to have anticipated common use cases, and catered to them. I need to convert dates in the format YYYY-MM-DD to DD/MM/YYYY. Here’s how you do it in Perl 5:

use Time::Piece;
Time::Piece->strptime($dstamp, "%Y-%m-%d")->strftime("%d/%m/%Y");

I don’t have to deconstruct the date stamp into components, and reassemble them. One line, and I’m done.

Later on in the program, I want to accumulate the balances for each account. I define the balances:

my %gaaps;

and I accumulate them:

$gaaps{$dr} += $amount;
$gaaps{$cr} -= $amount;

There are two magical things that P5 does for me here:

  1. Converts a string amount into a number
  2. Provides a default value for keys that are being newly defined

It’s basically taken away a lot of the “busy work” that you would have to do with other languages.

I had written a parser in lex and yacc for my C++ code in order to split out the input commands. It was useful experience. But I realised that I could do the job much more simply in P5 if I used split. I split a command into its name and arguments. Once I know the name, I know how may arguments it should take, and I could subsplit accordingly.

I could have achieved similar functionality in C++. C++ does, after all, include a regex library, and if I were to rewrite my program, that’s what I’d probably do.

I’d also like to mention Scheme here. I wrote a little module in chicken scheme, only to find that a macro I declared in the module couldn’t find a function that was defined in the module. I’m not sure what the problem is; I think it had something to do with when things are defined. Macros don’t fit well with Unix libraries, so I’m thinking that the scheme separated out the macros and defined them elsewhere, so it couldn’t see the definitions.

Plus, Scheme is rather a small language, and I had to install some extra modules. No biggie per se, but that’s additional infrastructural work.

And that’s kinda the point with the big, “serious” languages. They seem to have a lot of sharp corners. Things that don’t work the way you expect. Things that you have to set up. A lot of “accidental” complexity.

In short, P5 seems to have more “Do What I Mean” instead of me having to fuss over minutiae.

Faster than Python

Python is an excellent programming language. I want my code to work fast, even on a RPi2 (Raspberry Pi 2). Python isn’t “too” slow, but it’s slower than I find ideal.

I do have a lot of Python coding experience, and based on my experience with P5, the former doesn’t quite match the simplicity of Python.

What’s becoming clearer to me is that the designers of Perl (5 and 6) have sat down and thought to themselves “what do programmers typically mean and want when they use a certain construct in a certain way?” The designers have then gone away and made the language “do that thing.” Contrast that with the way that most other languages work: you have to specify behaviour.

I think this makes P5 an inherently more compact language, albeit possibly more dangerous.


P5 is on par with Python. Both are ubiquitous, with P5 maybe having the slightest of edges. It’s great when you don’t have to install a language on account of it already being there. Windows is an exception, of course, but they’re both easy to install.

Easy to learn

Despite not having programmed in P5 more than a handful of times, I find it surprisingly easy to pick up.

Simplify the problem

Can you really write an accounts package in a 100 lines of code?

Put it this way: by the time I’ve finished, I fully expect it to print financial statements, individual accounts, CGT prep work and portfolio export.

Programmers like to claim bragging rights to writing and managing behemoths. Such systems make you feel clever.

Bill Gates once wrote “Measuring programming progress by lines of code is like measuring aircraft building progress by weight.” Except that Bill Gates is a hypocrite. When has Microsoft ever made lightweightness a priority? Never, that’s when. The Windows way is to build large integrated solutions, in contrast to the Unix way, which is to build small solutions that can be married together in unexpected ways.

A man that I admire much more is Charles Moore, inventor of Forth. He decries standard software approaches, and says he can write code in a tenth of the size that most other people do. I am not in the same league as him by a long shot.

But what you must do is solve the problem. Nothing more. Maybe you can simplify the problem. Maybe you can remove assumptions that make certain problems disappear.

A lot of people have come away thinking that Moore is “quaint” and “naive”. Moore has done some amazing work. The stuff he has produced works for him. The rub is that they probably won’t work for anyone else. That’s undoubtedly part of his secret as to why everybody else’s code is at least 10X, 100X, 1000X more complex than Moore’s.

Not P6 (Perl 6)?

No. I’ve toyed around with P6. It’s very very slow, and I don’t think I could stomach it on a Pi 2, assuming that it works at all. Also, P6 is not available for Windows 32-bit architectures.

Posted in Uncategorized | Leave a comment

Newbies thoughts on #drracket and #scheme in general

I have toyed with scheme/lisp in the past. Like most people, I have thought “that’s really cool,” and then gone back to programming in whatever language I was using before.

Lisp, I found, has a high barrier to entry, and requires a lot of infrastructure to get it to do something useful. Yes, of course, you could just type everything at the REPL, but you’re probably going to want to integrate it with emacs and quicklisp. It’s a little unfriendly out of the box.

DrRacket is a nice implementation, with a nice out-of-the-box experience. It’s IDE is a little clunky and a little slow, but it comes with all sorts of goodies. I was interested in fooling around with language design, which is a key feature of DrRacket.

The problem with DrRacket is that although it’s a little sluggish on my trusty old desktop, it is dead slow on my Raspberry Pi 2, even without the GUI. So I decided to do a little experimentation with Chicken Scheme.

Chicken proved to be much more to my liking speed-wise. Its libraries are nowhere near those available out of the box as with DrRacket, which of course is to be expected. What I thought to be a big flaw with Chicken was its impenetrable error messages. I had to send my definitions to the REPL function-by-function in order to find out whereabouts its was complaining.

Then we come to this little “gem”:

open-output-file: … If a file with the given name already exists, the effect is unspecified.

Really? Each Scheme implementation is allowed to just make up its mind as to what it wants to do? And the library user has to check the behaviour against each implementation?

DrRacket has the most sensible way of implementing it. The default behaviour is to raise an error, but there are optional keys for alternative behaviour, like ‘replace.

That’s good, but DrRacket’s keyword syntax is not standard Scheme. It doesn’t look like it’s in the up-and-coming R7RS, either. This means that for library writers, there’s a good chance that the code won’t be cross-implementation compatible. Considering how long R7RS seems to have been brewing, it seems to be lacking some pretty fundamental design choices.

BWTFDIK. Those guys are smarter than me. I’m just wondering if the design committee has some kind of cohesive goal for Scheme. C++ seems much more coherent in their vision.

Just my uneducated 2c.

Posted in Uncategorized | Leave a comment

Magic Hat Portfolio: FXPO stays in

Metals & Mining company FXPO (Ferrexpo) is due to be kicked out of the portfolio by rotation. The market reacted badly to its recent trading statement, and it has a Stockopedia StockRank of 68. It is down 36.4% since purchase.

I would be happy enough to kick it out of the portfolio and swap it in for something else. FXPO still qualifies for the Greenblatt screen, though. It has a low PE and high yield. Its debt levels are reasonable. It seems like the kind of stock that would qualify for a “Dorfman Robot” portfolio.

Value shares could well be due for a comeback (Any Day Now TM), so despite my displeasure, I’m going to keep it in. We shall see.


Posted in Uncategorized | Leave a comment

#JPR: Johnston Press – in the news

JPR (Johnston Press) is trending on Twitter. It owns the Scotsman and Yorkshire Post, and it is looking to restructure or refinance its debt. Its share price is highly volatile, and claims that it “knows of no operational or corporate or other reason for the price movement.”

It share price is at 5.64p, giving it a market cap of £3.75m. Its revenue is around £200m, and Stockopedia gives it a momentum score of 3. Worrying!

Net debt seems to be £142m, and its only PBT since 2011 is £2.9m.

I would have thought that the situation was unsalvageable. If I held shares, I would sell out at any price.


Posted in Uncategorized | Leave a comment