First experience with std.algorithm: I had to resort to writing a 'contains' function.
Bernard Helyer
b.helyer at gmail.com
Tue Jun 8 04:23:39 PDT 2010
So I'm writing a compiler, and I wanted to create a list of TokenTypes
(an enum) and check to see if the current token is among them. 'A-ha!',
says I, 'I'll use std.algorithm!' (as I hadn't tried it really, yet,
except for playing around)
So I look it up, and find 'find'. It returns an iterated range, or an
empty range on failure. A little funky, but that's okay, I can swing it!
immutable TokenType[] someList = [TokenType.Foo, TokenType.Bar];
...
while (find(someList, tokenStream.peek.type) != []) {
doStuff();
}
If I have unittests on, this assert is triggered:
static assert(is(typeof(s) == Tuple!(string, float)));
I didn't at first, so I got another error. So I looked closer at the
documentation, and it turns out it needs an input range, and that needs
popFront! Well, it can't popFront an immutable range, so I dropped
immutable, and decided to let convention and TLS sort the rest out!
This worked. Until I turned unittests on, and the assert I showed above
tripped. At this point my language turned rather unpleasant and I wrote
this:
bool contains(T)(const(T)[] l, T a)
{
foreach(e; l) {
if (a == e) {
return true;
}
}
return false;
}
And my problems went away. I assume what I experienced is a bug, but I'm
not sure, so I thought I'd share my experience.
More information about the Digitalmars-d
mailing list