An esoteric #forthlang

I say Ulrich Hoffman’s talk on PreForth and seedForth the other day. Although I don’t understand much in the way of the details, the basic idea is to create a bootstrapping Forth.

This gave me the idea of creating a very very simple Forth. It is 123 lines of C, and is available here . I’ve called it fin. I originally intended it to be written in Nim (Forth In Nim, hence fin), but quickly switched to C.

Fin is a strange old beast. You are allowed 256 words. Each word is a character long. It has a normal stack, but doesn’t need a return stack. The dictionary is very simple: it’s just a lookup on a char. Here are the predefined words in Fin:

Primitives: ~ d - c k e
Inner words: ; x a
Outer words: : r h

So far, 12 words exist. There are no immediate words in Fin, and the only things you can do in the outer loop are:

: - begin the definition of a word
r - run the latest-defined word
h - halt the program

‘:’ calls ‘define()’. It simply writes out what is on stdin up to and including the ‘;’.

‘r’ calls ‘run()’, equivalent of ‘docolon’. It sets the IP (instruction pointer), executing each word that it finds, and exits when it finds a ‘;’. There are two other special instructions. ‘x’ exits the word if the top of the stack is non-zero. ‘a’ jumps back to the start of the word.

Primitives are defined via C. They are:

~ - the not operatord - dupe the top of the stack
- - arithmetic minusk - 'key' - read a char from stdin
e - 'emit' - write a char to stdout

This gives us just enough to write a hello world application:

:Ckdc.-~xea;rHELLO WORLD!.h

Groovy! We define the word C as out main loop. We read a key, duplicate its value on the stack, and compare it to the full stop. If we find one, we exit. Otherwise we branch to the beginning of the word.

Pretty cool. We may be asking “OK, so what’s the point?” Well, despite being a very very limited Forth, we might want to see if we can push it in a couple of interesting ways:

  • Can we add a couple of words to maybe produce a quine (i.e. a program that outputs itself)?
  • Can we bootstrap it so that we can produce an actually useful Forth?

We’re going to at least needs some words that manipulate the heap and the IP (Instruction Pointer). The question is: what’s the minimum we can get away with?

Maybe we could end up with “levels” of Forth, with each level adding features, and working faster, than the previous layer. The sorts of things we would want to implement would be conditionals, words of more than one character, spaces separating words, a proper look-up dictionary, and so on.

I think the first thing to work on would be a quine. That would require some heap manipulation, as we’d need to store the input. We’d also need to be able to have the concept of variables, maybe.

I shall develop this further.


Posted in Uncategorized | Leave a comment

Quickie: #rakulang vs #nim vs #rust vs #cpplang

I basically consider myself a C++ programmer, having decided to “standardise” on it a few years ago. I am a fan of Python, too.

I tried Rust, but in the end couldn’t see the point. Rust’s big idea is immutability. I don’t think it’s a big win, because C++ has “const”, so by careful programming, you can get C++ to behave properly. I understand that Rust has some other nice features to it as well. But in the end, C++ is the standard compiler. The standardisation efforts on C++ from 2011 has really sorted out C++ a lot. C++ gets you halfway to Python. In fact, I think it gets you more than halfway.

I am not a Perl 5 programmer, but I used it to rewrite my accounting module. Perl 5 scores big when programs are simple, and need to run fast, and where sed and awk aren’t quite up to snuff.

So, having touched on Perl 5, I decided to give Perl 6 (aka Raku) a go, and rewrite my accounting module in it. There are certainly some nice touches to Raku, like being able to bind multiple variables to results. And, if things don’t quite work, it gives sensible results.

Raku really does have some nice touches. Another one is gather/take. This is really cool, because of instead of a loop only accumulating an element on each iteration, you can accumulate as many, or as few as you want.

As I had said in a previous post, Raku has a lot of “do what I mean” to it, and it has a certain way to it. I describe it as having the quality that the language “thinks like a programmer thinks”.

Having said that, the language is dead slow, some of the syntax still puzzles me, and it won’t work on 32-bit Windows. I haven’t used Windows for at least 6 months now, but it would be nice to know that I could use Raku on it if I wanted to.

Whilst messing around with Raku, I heard of Nim. Initially, I wasn’t interested, figuring it was just another of those goofy languages. Here we go again, I thought, someone’s arbitrarily cobbled together syntax that largely does what every other programming language else does. But I looked at a few videos, and I became intrigued.

I am in the process of translating my accounting program. The syntax is intuitive, and approaches the brevity of Raku. Again, it has some nice features. I don’t really approve of space indentation as a syntax idea, especially when spaces are mandated instead of tabs. It makes it a fiddle for me to edit.

Other than that, the syntax is quite intuitive.

Although I haven’t explored the possibilities yet, what I’m really interested in is the notion of “types”. It has sum types (aka ADTs, abstract data types, or “variants”), and, get this, you can have recursive types. Hallelujah! Basically, Haskell typeclasses. This is one thing that C++ really needs, I think. The variants are a real pain to work with in C++. Lacking recursive types, it is also difficult for C++ to express the notion of a tree, which I want for doing parsing work.

I’ve expressed the view in the past that the ideal language would be some kind of “C++ meets Haskell”. Nim seems to have that idea in mind.

Nim also has templates. Not so much C++ templates on steroids, but C++ templates without the mind-splitting migraine. I haven’t explored Nim’s templates yet, though. What also intrigues me is that Nim has macros, something that Raku doesn’t have. Well, I still think Raku is trying to work out how macros are supposed to work. I think they’re going to be a bit fiddly, whatever they decide.

Nim is also way faster than Raku, on account of it being compiled.

Another nice touch about Nim is the ability to crosscompile easily. Cool! Now I can develop on my x86_64 machine, and create an executable for my Raspberry Pi. Very nice.

So, yeah, Nim is definitely interesting, and something that I want to dive into deeper.

If I had to choose only one language in the world, it would still probably be C++. C++ is absolutely ubiquitous, it’s modernisation efforts have really improved it, and, well, it gets the job done. Nevertheless, I intend exploring Nime further.

Just my 2 cents.

Posted in Uncategorized | 1 Comment

MKS drops 11%

M&S dropped 11% today on the back of its trading statement. LFL were up 0.2%. The RNS states “Trading reflects ongoing progress of transformation strategy.” I guess 0.2% constitutes progress, then. Gross margins are “expected to be around the lower end of guidance.”

So what we’re saying is that they did a lot of discounting, and their L4Ls are barely up. Worldwide, their revenues are actually down 0.7%.

I note that the market cap of M&S is £4.3b. It has an EV of £8.3n. That looks bad to me. Too much debt. Net profits have been in consistent decline since at least 2014. Offhand, I’d say that things need to improve real soon, or else they start finding themselves in jeopardy. Difficult to imagine such an august company going to the wall, isn’t it? Still, it happened with Thomas Cook, and it looks like dear old Marks & Sparks is heading down that route.

Paul Scott is much more optimistic, and sees MKS as a long-term winner. He is tempted to buy in.

Seems to be a bit of a batman formation on the charts, there. Just thought I’d throw that one out there.

In related news, John Lewis could axe staff bonus for first time since 1953, according to Yahoo Finance. The pressure on the high street seems relentless. It’s amazing how things still haven’t stabilised.

I haven’t shopped in John Lewis for years, but my view on them at the time  was that they’re rather pricey. I would rather shop elsewhere for stuff that I thought was cheaper but still offered reasonable quality.


Posted in Uncategorized | Leave a comment

CARD drops 29%

Wow, this one really took a massive dump. On the carpet. In front of the vicar.

I hold this share. It was my biggest faller in my portfolio, and it just got worse. I’m nursing a 50% loss on this. Ouch. I bought it back in May 2019 when it had a dividend yield over 4%, and the shares had good momentum.

What’s very interesting is, looking at the chart, CARD failed to participate in the Santa rally. It seems that Mr. Market was anticipating weakness.

Paul Scott mentions CARD in his latest report over on Stockopedia. He is long the stock, so I can at least console myself with the fact that I’m in good company. He classes the RNS as a mild profit warning, and pointedly states that the company is obscuring the figures for xmas trading. He sees value at 100p, having bought in at 140p.

At 9:10am, shares were down 21%. A director made a purchase of £11k. The shares slid further. As Paul states:

the CEO has just bought a paltry 10,000 shares today. If that was designed to show confidence, it’s back-fired. If the CEO is only prepared to risk £11k of fresh money on buying shares, then that worries me, more than reassures me.

I wholeheartedly agree with that! I take the purchases as a bearish point.

My plan is to hold onto the shares for now, as the drop has been highly precipitous. Hopefully I’ll get some recovery in the share price with a firm view to sell in May.

Not one of my better picks. Anyway, you can read Paul’s detailed analysis in the link provided.

Stay safe out there.


Posted in Uncategorized | Leave a comment

“Beautiful” recursive descent grammars using C++ short-circuits

I am author of ‘neoleo’, a curses spreadsheet forked from the abandoned GNU oleo project.

One thing I’m doing is rewriting the parsing of spreadsheet formulas using recursive descent parsing instead of yacc/lex.

Recursive descent parsing traditionally looks like a lot of manual coding. But I think there’s a better way: using the C/C++ standard-mandated short-circuiting mechanism of && and ||, and possibly a few others.

Take one section of the parser, where I parse for a cell reference. A cell ref may either be a number, or enclosed in brackets, like so: “42” , or “[42]”. Now, if you were to write it using “code”, you would have to look at the next token, and decide if was a “[“, then look for a number, then a “]”, or else it is a number, or else it is a parse error. Here is the actual implementation of that function:

bool abs_or_rel(tokens_t& tokes, CELLREF& n, bool& relative)
        relative = false;
        auto set_relative = [&relative]() {relative = true; return true;} ;
        return (is_char(tokes, '[') && is_cellref(tokes, n) && is_char(tokes, ']') && set_relative() )
                || is_cellref(tokes, n)
                || parse_error();

Note that it looks rather like a grammar rule without much in the way of boilerplate code. The && and the || almost act as a DSL for you. They are just the standard C/C++ logical and and or operators. I haven’t defined them specially. The magic comes from the fact that C/C++ uses short-circuiting in these logical operators to follow the choices or not.

Now tokens_t is a vector of tokens. “Tokens” are pairs consisting of the token type (a number, string, etc.) followed by its actual value, in string form. Passing the value in string form is more convenient. If you need to convert it to something else, like an actual number, then you can.

So, is_char() takes the vector of tokens, and compares it against the supplied char. If there’s a match, then it pops off a token, and returns true. Otherwise it returns false. is_cellref() does a similar thing. If expects a number (although negative is allowed). If it finds one, it pops the token, sets the value for n, and returns true. Otherwise it returns false. Here are their implementations:

bool is_char(tokens_t& tokes, char c)

        if( tokes.front().first != c)
                return false;
        //cout << "is_char:" << c << ":true\n";
        return true;

bool is_cellref(tokens_t& tokes, CELLREF& ref)
        bool neg = is_char(tokes, '-');

        if(tokes.front().first != NUMBER)
                return false;
        ref = stoi(tokes.front().second);
        if(neg) ref = - ref;
        return true;

It is a mechanism that is quite general. I believe that you can vastly improve the readability of recursive descent parsing code by adopting this “trick”.

Posted in Uncategorized | Leave a comment

The death of Value

Earlier this year (OK, yesterday) I mentioned Paul Scott’s comment about him seeing good value in small caps, assuming I haven’t misremembered what he said.

By coincidence, I came across an article by StarCapital from Nov 2019 on “The presumed end of the Value premium”.

They state:

Over the last five years, Value stocks have underperformed Growth stocks by an average of nearly 6% per year …the current drought belongs tothe 1% of the worst underperforming market periods in history
And importantly:
While European Growth stocks, for instance, have been valued on average 78% higher than Value stocks in former decades, this valuation premium has recently climbed to 156%. Only in spring 2000, immediately before the bursting of the dotcom bubble and before the beginning of one of the strongest value periods ever, the level of overvaluation of Growth companies was comparably high. Even then, in the wake of technological innovations, the idea of value investing seemed outdated
Their figure 6 is interesting. Of the top ten biggest companies of the decade, only about two will remain so in the next decade.  Only Microsoft made it for 3 straight decades.
So I’m increasingly favouring value, and might weigh that heavily into my decisions as to what to buy.
You might also like to take a look at the Stingy Investor site, which has been around for a long time, and has some interesting articles.
Stay safe out there.

Update 1: In Oct 2018, IBD posted an article stating that

Value stocks have underperformed so dramatically since 2010 that growth stocks now hold the upper hand over the past three decades

They warn that

Unlike during the dot-com bubble, growth stocks don’t look especially expensive relative to value. Thus, there’s no reason to expect a big reversal this time. … The P/E evidence indicates that growth stocks have earned their way to their success, rather than being buoyed by higher investor sentiment

I will conclude this update by noting that RDSA (Royal Dutch Shell), according to Stockopedia, is trading on a PE of 11.3, has a yield of 6.2%, and a P/FCF of 7.9. I think of a P/FCF<10 as offering excellent value. Given the political unrest between US and Iran, oil is expected to increase in price. I am therefore bullish on RDSA, and have some in my portfolio.

Update 2: There’s an article on abovethecanopy that offers the following statistic:

Over 5 year intervals value outperforms growth 75% of the time, and over 10 year periods 84% of the time.

Update 3: An article by CFA Institute from August 2018 offers a compelling explanation as to why  growth has beaten value over the last decade. The explanation is simple: after the banking crisis, value and growth stocks were trading at nearly the same earnings ratios. Growth stocks then went on to expand their earnings ahead of value (because that’s what growth stocks do). So naturally, growth stocks did better. The PE ratios were similar in 2017, but then diverged, with growth PEs rising, and those of value falling. Interesting, isn’t it? The graph only goes up to Jan 2018, and we don’t see the relative values as they stand now.

Posted in Uncategorized | 1 Comment

Time to sober up?

Aye aye, looks like trouble is kicking off for the new year. The issue is oil. My portfolio is down 1% today, a little more than the indices. I have a small position in Shell, which of course is doing well, up 1.5% today. That doesn’t compensate for the broader falls in my portfolio.

It looks as though Santa has headed back to the north pole and we’ll have to work off some of that alcohol-induced euphoria. We’ll see, though.

The BBC carries the news: “Oil prices have risen sharply after the killing of a top Iranian general in Iraq. Analysts warned the action could escalate tensions in the region and affect global oil production.”

At first I thought it could just be a storm in a teacup, but the article continues: “It came after General Qasem Soleimani was killed in a US drone strike at Baghdad airport, which the Pentagon described as “defensive action”. … Iran vows ‘revenge'”


Stay safe out there.

Posted in Uncategorized | Leave a comment