elvish shell

I decided to give the elvish shell a try today. Elvish is a shell written in golang, designed to be more expressive than bash.

Bash drops just short of being a programming language. For example, it doesn’t do floating point arithmetic, which is a nuisance. Elvish does, though.

I set myself a little task: write a program which reads from standard in, prints the number of lines read, then prints the input. It’s an interesting task because it must cache the input.

Here’s what I cam up with in elvish:

#!/usr/bin/env elvish
contents = [(cat )]
echo (count $contents)
for line $contents { echo $line }

Here’s the equivalent I write in awk:

{
 i += 1;
 line[i] = $0;
}

END{
 print i;
 for(idx=0; idx<i; idx++) print line[idx];
}

As you can see, elvish manages the same thing in less than half the number of lines.

Here’s my C++ version:

#include <iostream>
#include <string>
#include <vector>

int main()
{
 std::vector<std::string> lines;
 std::string line;
 int nlines = 0;
 while(std::getline(std::cin, line)) {
 nlines++;
 lines.push_back(line);
 }

std::cout << nlines << "\n";
 for(std::vector<std::string>::iterator it = lines.begin(); it != lines.end(); ++it)
 std::cout << *it << "\n";

return 0;
}

That’s 20 lines of code.

Here are the timings of running the scripts:

time awk -f count.awk <derive-2.txt >/dev/null
real 0m0.067s
user 0m0.004s
sys 0m0.002s

Although there are some odd timings:


time awk -f count.awk <derive-2.txt >/dev/null

real 0m0.006s
user 0m0.003s
sys 0m0.002s
$time elvish count <derive-2.txt >/dev/null

real 0m0.052s
user 0m0.025s
sys 0m0.011s
time ./a.out < derive-2.txt >/dev/null # c++ version

real 0m0.006s
user 0m0.004s
sys 0m0.001s


Awk seemed a little inconsistent in its performance. I’m not sure what’s going on there. It looks like Awk can be a real speed demon, and I’ve even seen it run a little faster than the C++ code. Those Awk guys certainly seem to know how to optimise stuff.

Elvish is certainly worth checking out. I’m not sure about its runtime speed, though.

Advertisements
Posted in Uncategorized | Leave a comment

A s-expr interpreter in #cplusplus

I have been working on my interpreter, and switched from parsing BASIC to parsing s-expr. The code is available on github. It’s crude, to be sure, and the inputs are fixed, but it does handle parse trees.

You can define variables, and it has a single arithmetic operator: addition. It’s really just a proof-of-concept. It’s quite a large amount of code, at just over 450 lines. I would really like to reduce the code base.

My goal is to come up with a kind of “pre-Scheme”, a language from which parsers can be created. I had planned to make the functionality extensible, but so far I have hard-coded the funtion definitions into blang_apply(). I am confident that the code could easily accommodate my proposed modifications.

The main class is “cell”, which holds a variant type. I actually used the C++ 2017 variant type at one point, but I couldn’t figure out how to set a value. I have abandoned that representation, as I grew frustrated with trying to make it work.

One thing I notice about C++ is that I often find that “some hammering is required”. Sum types (aka algebraic data types) fit naturally into Haskell syntax.  C++ seems to require a lot more effort.

This is an interesting philosophical question: should C++ by expanded by classes, or by syntax extensions? Classes certainly have one big advantage: you don’t need a new compiler. But they do have the disadvantage in that syntax can be easier to work with. After all, if product types are part of the language, then why not sum types?

Regardless of that, I now think my cell class is too unwieldy. Just as I planned to have a plug-in functions, I now think it is a good idea to have plug-in types.

One approach to types would be to use C++ class hierarchies to achieve polymorphism. I think that is the wrong approach, though. That would make it more difficult to extend dynamically. I prefer the idea of having “slots” for construction and destruction.

The current implementation keeps with the tradition of its previous incarnation as regards to deterministic garbage collection. No garbage collector is necessary.

Posted in Uncategorized | Leave a comment

Magic Hat – HVN stays in

The MHP (Magic Hat Portfolio) on Stockopedia (http://www.stockopedia.com/fantasy-funds/magic-hat-463/) is an experiment by me to see if a human can improve on a mechanical Greeblatt Magic Formula screen. I am trying to weed out “mistakes” that I feel the screening commits: unseasoned companies, scams, foreign companies (particularly Chinese), fishy accounting, and statistical quirks. Apart from that, I am agnostic as to the sector the company operates in, although I will try to avoid heavy concentration in any one sector. I will mostly apply “Strategic Ignorance”, by which I mean that I wont try to be clever in my stockpicking. My picking will be mostly mechanical. A summary of most of my Magic Hat articles can be found on the web page http://www.markcarter.me.uk/money/greenblatt.htm This will allow you to see, at a glance, what shares have been bought and sold in the past, as well as what shares have been rejected from consideration and why.

HVN is due to be ejected from the portfolio by rotation, but seeings as it still meets with the Magic Formula criteria, it stays in. It has a StockRank score of 98, also making it a keeper. The company has returned 27% since holding it a year ago, which is a very nice return.

The Magic Hat portfolio has come off the boil since May 2017; a phenomenon which I feared would happen.

Stay safe out there.

Posted in Uncategorized | Leave a comment

Arch Linux vs Slackware vs Others

Slackware was the first distro I installed, from a book, in the early 90’s, when I was studying for my PhD. In the latter half of the 90’s I had installed Redhat.

For everyday use, I use Windows, because things like my webcam and Yahoo Messenger Just Worked. If I was feeling a bit UNIXy, it was always possible to resort to cygwin.

I mostly pootled along that way until I discovered the Raspberry Pi, whereupon I decided to run a webserver from home on it. I fiddled around with the hardware, bought a cubieboard, and then a proper computer: an ASUS. The ASUS was pretty cheap. It came with Windows 8, but with no install disk, alas.

I tried Windows 8 for all about 30 minutes, and concluded that it was as bad as everyone said it was. That’s when I decided to zap the hard drive and install Arch onto it. I had some experience with Arch before, which gave me problems, for one reason or another.

I knew that my server would be dedicated to Linux, so I did not mind that I was erasing Windows 8.

This time, I had no problems with Arch, and I have been using it on my server for over a year. My conclusion: it’s the best Linux OS I have used. Despite being rolling release, it has been very stable for me, and much more stable than other systems.

On my main desktop, I have mostly been using Windows 7, with the occasional dual-boot to whatever I happen to want to experiment with. I have used a number of Linux systems in the past, including the *BSDs.

I usually dual-booted onto some flavour of Ubuntu; either the main distro, or Lubuntu. I tried out the most recent version of Ubuntu to see what all the fuss was about regarding the GNOME desktop.

To me, GNOME is unusable. It seems to require an unwarranted amount of movement, with no particularly good way of arranging windows. It you’re a developer, you need to have ready access to a large number of windows, and GNOME doesn’t seem to accommodate that kind of layout.

I was irked enough that I decided to try Slackware again.

My general comparison of Arch vs Slackware:

  • I love the breadth of packages available for Arch, and its dependency management. Slackware is clearly inferior in that respect … BUT … having said that, Slackware has two mitigating factors: 1) alienbob provides some pre-built binaries, and they’re for some really useful software like vlc, blender and libreoffice, and 2) failing that, sbopkg fills in many gaps. I discovered the tool ‘sqp’, which can build a queue containing all the dependencies. This is excellent, as it means I don’t have to fark around manually installing the dependencies. The dependency chain can be quite long for some of the more involved packages. Now I don’t have to worry about it. For software that is not in sbopkg, I can download the source and compile. This is not so bad, because software in this category tends to be at the periphery, where the dependency chain is not so big as to be onerous. Arch still wins, but I now feel that Slackware is able to make an adequate showing.
  • I am not a “ooh shiny” kind of guy, but I think that the newness of Arch software is a net plus. People’s mileage is going to vary on this. Some won’t like the size of the updates, and some won’t like the potential stability issues. Also, personally, I am keen to develop in C++17, so I am always itching to see what’s in the latest GNU compiler. Contrariwise, I think Slackware is great for testing your releases, as it is somewhat older, and you can check for compatibility issues. So it’s a win for Arch for me.
  • systemd … Slackware wins by not having it.

So, generally, I prefer Arch, although I think Slackware is an adequate second. I intend to dual-boot into my Slackware distro more often, and I would say that my opinion of Slackware has actually increased in the last week.

As to my opinion on other distros:

  • Ubuntu: I would actually recommend it for most people. It has some wonks to it, and I don’t like GNOME, but for most others it should be fine
  • Mint: pretty good, although I haven’t used it for a few years
  • Other minor distros like Crunchbang, Puppy, Elementary, etc. … yeah, they’re OK, pretty good, if they work for you, fine, but I always migrate away from them eventually
  • Debian: I have a lot of respect for Debian. apt-get is great. Stable is too old, and I wouldn’t recommend Stable for most people. Testing would be a much better bet, although I do notice that even in Testing, software can be somewhat stale. Sid, just no, I don’t want to “keep both pieces”. I’d say that if you wanted to install Debian, you’re actually probably better off installing Ubuntu.
  • Gentoo: no thanks. Seems like a hammer to crack a nut.
  • Fedora … ah yes, Fedora. this distro I have to rate as utterly unusable. By which I mean: eat flaming death, preferably with Poettering still trapped inside the building. Everyone would be much better advised to install Ubuntu instead. And before any Fedora fanboy pipes up in defense: please save your breath, I’m aware of the arguments, but I don’t buy them.

On desktops:

  • GNOME: Gno thank you. Consumes a lot of resources but delivers little functionality. The worst desktop environment imaginable.
  • KDE: OK, but not for me. Too resource-hungry for my liking, and a bit overly sugary, if you take my meaning
  • XFCE: I used to like it, but it now seems fairly resource-hungry and too finicky to set up
  • Fluxbox and LXDE: my two favourite window managers. Light-weight, stays out of my way, and yet has enough features to be useful. I discovered that you can do aerosnapping on Fluxbox, which makes it all you really need. Both are a little bit of a pain to set up to an acceptable configuration, but once done, they are great desktops
  • Fvwm2: I’m a fan of retro, and this certainly has that 90’s desktop feel to it. It’s a very light-weight manager, and apparently very customisable. The lack of a panel is a severe letdown, and the button bar and pager seem a bit clunky to me; which is why I prefere Fluxbox/LXDE better
  • Tiling window manager: fun for about 5 minutes of geeking out, then it’s back to a regular window manager as pragmatism reasserts itself

So there we have it. That’s my rant over. Remember, if you disagree, they’re only opinions. But they are the right ones. 😉

Posted in Uncategorized | Leave a comment

Follow-up on HSBA and CPR

Having being 100% right on my last post, I now find myself being 100% wrong. I am reminded of the joke about the scientist: “Our new drug showed an efficacious effect on one third of our chicken test subjects, little or no improvement on another third of our chickens, and I’m afraid the last chicken ran away.”

Six months ago, I was bearish on both HSBA (HSBC) and CPR (Carpetright), and promised to write up about their subsequent performance.

On HSBA, I wrote:

The reaction to the trading statement suggested that it was likely to be a busted trade.

An alert was triggered earlier today, indicating that the price fell below that, so I sold. I managed to achieve a little over 645p, dealing costs included. So I lost 2.1% on the trade. Disappointing, but of course less disappointing if the shares decline more.

So, to sum up, I had concluded momentum was lost, and I expect further declines in the share price thereafter.

The shares now trade at 742p, so I lost out on a considerable potential gain.

On CPR, I wrote:

What attracted me was the likelihood of momentum reversal. It’s momentum score is 14. A mere glance at the chart shows you that momentum is bad in any event. Its value score is 87. So here we have an interesting situation. The shares are cheap, the momentum has been bad in the past, but it is now trading above its 50dMA in what appears to be a reversal of trend. What’s more, on 31 Jan 2017, it issued its Q3 trading update, which raised the share price 8.8%.

CPR reminds me of DTG (Dart): terrible momentum, cheap, but with a trading update that caused a re-assessment of the company.

So I am going to stick my neck out and say that I expect the share price of CPR to be higher in 6 months time than it is now.

Alas, it was not to be. The shares traded at 208p at the time, and now trade on 194p. The shares have languished over the last 6 months. Its value score has been reduced to Stockopedia 76. Paul Scott had this to say at the end of June:

this share looks quite good superficially. However, it’s the type of share where, the more you dig into the numbers, the less impressive it looks.

There have been no divis paid since 2011 either, which isn’t good. Although a small divi is forecast for the new year.

Look how brokers have been steadily revising down forecast EPS in the last year, which hardly seems to be a business in rude health, does it?

So, not much to be excited about, especially since its overall StockRank score is an indifferent 50.

Stay safe out there.

Posted in Uncategorized | Leave a comment

A simple BASIC interpreter in C++

Writing an interpreter is something every programmer wants to have a go at at some point. I wanted to see if I could write a recursive-descent interpreter for the BASIC programming language using modern C++. There is some malice afore-thought, as I am also investigating the use of a programming language for my spreadsheet program neoleo.

I have called my language blang, derived from Basic language. What I like about it is that it is contained in one file, and is reasonably short, at 649 lines. It has if-then-else, for-next, let, print, while-wend and limited support for strings. It has no functions, or gotos.

The code is not perfect, but it shoud be comprehensible, and act as a base for those wishing to explore interpreters.

The idea is that each syntax element has a class with two parts to it:

  • a parser, held in the object’s constructor, that is able to parse the element in question, and dispatch to other elements as required
  • an evaluator, which, obviously enough, evaluates the stored parse expression.

Here is the class declarator for a statement:

class BlangStmt: public BlangCode { // some statement
	public:
		BlangStmt();
		void eval();
	private:
		unique_ptr stmt = nullptr;
};

A top-level statement handles lets, fors, ifs and whiles. Here’s its implementation for the parsing stage:

BlangStmt::BlangStmt() {
	string sym = nextsymb.value;
	nextsymb = yylex();
	if(sym == "print")
		stmt = make_unique();
	else if(sym == "let")
		stmt = make_unique();
	else if(sym == "for")
		stmt = make_unique();
	else if(sym == "if")
		stmt = make_unique();
	else if(sym == "while")
		stmt = make_unique();
	else
		throw runtime_error("Statement unknown token: " + sym);
}

Quite small. Notice what is not handled, though: the else, fi, wend, next statements. That is delegated to another class. Else and fi are handled by the BlangIf class, for example.

The evaluator for BlangStmt is on of the most straightforward evaluators:

void BlangStmt::eval()
{ 
	stmt->eval(); 
}

It just delegates the evaluation to whatever statement it creates. Here is how the if statement is implemented:

class BlangIf: public BlangCode { // if .. then .. [else ..] fi
	public:
		BlangIf() {
			rel_ptr = make_unique();
			checkfor("then");
			bool processing_then = true;
			while(nextsymb.value != "fi") {
				if(nextsymb.value == "else") {
					processing_then = false;
					nextsymb = yylex();
					continue;
				}
				if(processing_then)
					then_stmts.push_back(make_unique());
				else
	 				else_stmts.push_back(make_unique());
			}
			nextsymb = yylex();
		}

		void eval() {
			if(rel_ptr->get_value())
				for(auto& s: then_stmts) s->eval();
			else
				for(auto& s: else_stmts) s->eval();

		}
	private:
		unique_ptr rel_ptr;
		vector then_stmts, else_stmts;
};

You can read the whole source code for how other statements, including relational operators, work.

Because it’s a recursive-descent parser, some classes are defined in terms of other classes in in mutually-recursive fashion. This is sometimes considered “bad form”, but it is just an expression of the underlying algorithms. A little bit of sheparding of class definitions and declarations are required. You need to forward-declare some classes, and sometimes separate the class prototype from its implementation.

I have in mind the idea to completely re-write the code. The parsers contain quite a lot of “grunt work”, compared to their BNF form. Here, for example, is the BNF for parsing numerical expressions:

E --> R {( "<" | "<=" | ">" | ">=" | "==" | "!=" ) R}
R --> T {( "+" | "-" ) T}
T --> P {( "*" | "/" ) P}
P --> v | "(" E ")" | "-" T

It is very simple and readable compared with the code that implements it, relatively speaking. So the plan would be to write a meta-parser: one that could take BNF expressions as a way of transforming the target language into a source tree. The code for the interpreter would be much simplified: the bulk of the code would go in the evaluator.

Except … let’s back up a bit. If we’re going to write another interpreter, then let’s see what the easiest one to implement there is. The answer to that question is: s-exprs.

So, a simplistic Scheme-like interpreter could be made that has injectible functionality. S-exprs are very easy to parse, and you can extend them.

We see, in the example above, the definition of E as being list-like. There are many similarities between the definition of E and R and T. So perhaps, instead of the BNF above, we might write:

(def-form E (repeat-end ( "<" | "<=" | ">" | ">=" | "==" | "!=" ) R)

This may facilitate the evaluator, because it’s a kind of pattern that is common, and can therefore be abstracted. Instead of the evaluator having to chug through a vector of operators and sub-forms, it could define a function that knows how to reduce these vectors, which could be passed into std::accumulator, or something.

There are some exciting possibilities that I want to explore here.
index.png

Posted in Uncategorized | Leave a comment

CLLN – now what?

Mr. Market has been in a real punishing mood lately, and has not been afraid of clobbering even the largest companies.

Scanning Hargreaves Lansdown’s Biggest Fallers list, I see that construction and engineering company CLLN (Carillion) is down 13.6% to 41.7p. Stockopedia classifies it as a value trap, and gives it a momentum score of 0. A company must have done something seriously wrong to warrant a momentum score like that.

There doesn’t appear to be any news issues today, so I’m not clear what the fuss is about. However, I notice that yesterday they issued a statement saying that they will issue a trading update on the interims on 29 Sep 2017. That’s a Friday, the last day of the month. Last year, they issued the interims on 24 Aug 2016, more than a month earlier. There is one big implication to this, in my view: you ain’t gonna like what you’ll read.

John Kingham tweeted his article “What you need to know to avoid the next Carillion” recently. I recommend reading it highly.

Brace for impact.

41.7p

XJ2L4pOd.jpg

Posted in Uncategorized | Leave a comment