I am trying to use the fold operation on a range returned by byLine(). I want the lambda which is passed to fold to be a multi-line function. I have searched google and read the documentation, but cannot find a description as to what the signature of the function should be. I surmize that one of the pair is the accumulated sum and one is the current element. This is what I have but it will not build
auto sum = File( fileName, "r" )
.byLine
.fold!( (a, b)
{
auto len = b.length;
return a + len;
});
The error I get back from dmd is:
main.d(22): Error: no property `fold` for `(File(null, null)).this(fileName, "r").byLine(Flag.no, '\n')` of type `std.stdio.File.ByLineImpl!(char, char)`
So my question is two fold:
I have tried searching google and reading the dlang documentation for fold. All documentation uses the shortcut lambda syntax (a, b) => a + b.
So the way fold works is that it accepts a list of function aliases on how to fold the next element in. if you don't provide it with a starting value, it uses the first element as the starting value. Quoting the documentation (emphasis mine):
The call
fold!(fun)(range, seed)first assigns seed to an internal variableresult, also called the accumulator. Then, for each element x in range,result = fun(result, x)gets evaluated. Finally,resultis returned. The one-argument versionfold!(fun)(range)works similarly, but it uses the first element of the range as the seed (the range must be non-empty).
The reason why your original code didn't work is because you can't add an integer to a string (the seed was the first line of the file).
The reason why your latest version works (although only on 32-bit machines, since you can't reassign a size_t to an int on 64-bit machines) is because you gave it a starting value of 0 to seed the fold. So that is the correct mechanism to use for your use case.
The documentation is a bit odd, because the function is actually not an eponymous template, so it has two parts to the documentation -- one for the template, and one for the fold function. The fold function doc lists the runtime parameters that are accepted by fold, in this case, the input range and the seed. The documentation link for it is here: https://dlang.org/phobos/std_algorithm_iteration.html#.fold.fold
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With