Trying to search a range

Paul Backus snarwin at gmail.com
Sat Jul 3 01:15:20 UTC 2021


On Saturday, 3 July 2021 at 00:29:23 UTC, Kevin Bailey wrote:
> Unfortunately, ldc2 is saying:
>
> ```
> split.d(8): Error: template std.algorithm.searching.findSplit 
> cannot deduce function from argument types 
> !()(ByLineImpl!(char, char), string), candidates are:
> /usr/lib/ldc/x86_64-linux-gnu/include/d/std/algorithm/searching.d(2882):        findSplit(alias pred = "a == b", R1, R2)(R1 haystack, R2 needle)
>   with pred = "a == b",
>        R1 = ByLineImpl!(char, char),
>        R2 = string
>   must satisfy the following constraint:
>        isForwardRange!R1
> ```

The error message here is actually telling you exactly what the 
problem is: `findSplit` requires a forward range, but the range 
returned by `File.byLine` is not a forward range, just an input 
range.

     import std.range;
     pragma(msg, 
isForwardRange!(typeof(File("somefile").byLine())));
     // prints "false"

The difference between an forward range and an input range is 
that forward ranges implement `.save`, a method that allows you 
to save your place in the range and return to it later. The range 
returned by `File.byLine` doesn't have this method because it's 
not always possible to save your place in a file (for example, if 
you're reading from a pipe).

To work around this, you can either (a) read the whole file into 
memory before using `findSplit` on it, or (b) redesign your 
algorithm to work in a single pass over the input file.


More information about the Digitalmars-d-learn mailing list