First experience with std.algorithm: I had to resort to writing a 'contains' function.

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Tue Jun 8 06:44:06 PDT 2010


On Tue, 08 Jun 2010 23:23:39 +1200, Bernard Helyer wrote:

> [...]
> 
> 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!


Actually, there is no reason this shouldn't be possible.  This works:

    import std.array:  popFront;

    immutable(int)[] tail(immutable(int)[] list)
    {
        list.popFront();
        return list;
    }

    void main()
    {
        immutable a = [0, 1, 2, 3];
        assert (tail(a) == [1, 2, 3]);
    }

The problem is that find()'s parameters are templated, so when you give 
it an immutable(int[]), it doesn't know it's safe to treat it as an 
immutable(int)[].

find() should probably be improved to allow this.  I'm sure this won't be 
the last time someone tries to search an immutable array.

-Lars


More information about the Digitalmars-d mailing list