Ranges tutorial

Johann MacDonagh johann.macdonagh.no at spam.gmail.com
Sat Jul 16 13:29:12 PDT 2011


On 7/16/2011 4:13 PM, Willy Martinez wrote:
> == Quote from Johann MacDonagh (johann.macdonagh.no at spam.gmail.com)'s article
>> However, for what you want, you can use std.algorithm.filter
>
> OK. Followed your advice and this is what I've got so far:
>
> import std.algorithm;
> import std.file;
> import std.stdio;
>
> void main(string[] args) {
> 	auto needle = boyerMooreFinder(args[1]);
> 	foreach (string name; dirEntries(".", SpanMode.shallow)) {
> 		if (name[$-3 .. $] == "txt") {
> 			writeln(name);
> 			string text = readText(name);
> 			auto haystack = filter!("a>= '0'&&  a<= '9'")(text);
> 			auto result = find(haystack, needle);
> 			writeln(result);
> 		}
> 	}
> }
>
> Passing the haystack filter to find() produces the following error:
>
> ..\..\src\phobos\std\algorithm.d(2912): Error: function std.
> algorithm.BoyerMooreFinder!(result,string).BoyerMooreFinder.beFound (string
> haystack) is not callable using argument types (Filter!(result,string))
> ..\..\src\phobos\std\algorithm.d(2912): Error: cannot implicitly convert
> expression (haystack) of type Filter!(result,string) to string
> ..\..\src\phobos\std\algorithm.d(2912): Error: cannot implicitly convert
> expression (needle.beFound((__error))) of type string to Filter!(result,string)
> search_seq.d(12): Error: template instance
> std.algorithm.find!(Filter!(result,string),result,string) error instantiating
>
> What could be the problem?
>
> Thanks

Oh, I didn't see you wanted to do a Boyer-Moore search in your original 
post. Dmitry basically explained what's wrong.

filter is lazy. When you do auto x = filter!... it doesn't filter right 
away. It filters as you iterate over the range (this makes it much more 
efficient). This means you can't find the xth element of a filtered 
range (well you could, but it's not in O(1) time, which is why a 
filtered range doesn't expose indexing operators).

You'll want to use array() over the filtered range that filter returns. 
This will iterate over the entire filtered range and pull out each 
element into an array. An array can be randomly accessed, which 
Boyer-Moore needs. See Dmitry's post in your other topic.


More information about the Digitalmars-d-learn mailing list