wc in D: 712 Characters Without a Single Branch

Steven Schveighoffer schveiguy at gmail.com
Tue Jan 28 14:44:14 UTC 2020

On 1/28/20 9:01 AM, Mike Parker wrote:
> Robert Schadek was inspired by a post he saw on Hacker News a while back 
> showing an implementation of wc in Haskell totaling 80 lines. He decided 
> he could do better in D. So he did. This post on the D blog shows what 
> he came up with and also provides a brief introduction to ranges.
> The blog:
> https://dlang.org/blog/2020/01/28/wc-in-d-712-characters-without-a-single-branch/ 
> Reddit:
> https://www.reddit.com/r/programming/comments/ev5w91/wc_in_d_712_characters_without_a_single_branch/ 
> It's also on Hacker News, but please don't post a direct link to it if 
> you find it there.
> https://news.ycombinator.com/

Nice! I bet you get better performance with a tweak: you are currently 
iterating each line 2x (3x if you count searching for the line ending).

If you did both at once, the toLine function would be longer, and 
probably have some branching in it. But I bet you get close to double 
performance for that.

You could also combine all 3 checks into one (if you are checking for 
spaces, you might as well check for newlines). But newline searching is 
pretty fast for byLine. iopipe could probably do a bit better ;)

In any case, I totally get what you are saying: 15 minutes to write a 
program that works, is easily understandable, but has performance issues 
for unusual input is pretty cool.


More information about the Digitalmars-d-announce mailing list