the Result Type

Marco Leise Marco.Leise at gmx.de
Sun Dec 8 02:07:23 PST 2013


Am Sun, 08 Dec 2013 09:24:53 +0100
schrieb "seany" <seany at uni-bonn.de>:

> std.algorithm.splitter seems to return all its return values as a 
> type "Result", without quotes, and i dont not seem to be able to 
> cast it to string[] or int[]  with cast(string[]) ( or even cast 
> (string) - i tried that too).
> 
> I tried to use a function
> 
> void function(T, R)(T arr, out R output)
> {
> 
> foreach(elem; arr)
> {
>      output ~= elemM
> }
> }
> 
> i have an occasion where R is int[], and one where it is 
> string[]; and
> but it says, that int can not be appended to string[], and string 
> can not be appended to int[], and compilation fails.
> 
> Nonetheless removing either of the occasions, solves it.
> 
> how to deal with  this Result type?

That confused me as a beginner as well until I understood that
these Result types are actually just structs. They are
generated at compile-time and share commonly known methods
like .front or .popFront() that identify them as "ranges".

Arrays are a sub-set of ranges. The algorithms in D typically
take a range as input and a range as output. Where possible
they try not to go over the whole input at once, but only as
needed. This is called lazy evaluation and is one reason you
don't get returned a complete array. In some cases the input
might even be infinite: Try returning an array for splitter
over a random number generator as input range!

So what do you do with a Range struct? There are 3 options:
* If you really want an array you can call the function
  array() on the Result:
  http://dlang.org/phobos/std_array.html#.array
* If you want to further process your Result with other
  algorithms, just chain them together. E.g.:
  arr.splitter("abc").sort.uniq();
* If you want to iterate over the Result, foreach works on
  those Result ranges:
  foreach (elem; arr.splitter("abc")) {...}

The range concept makes it easy to apply any kind of algorithm
on stuff that can be represented as a consecutive items of
the same type. And it allows those algorithms to only do as
much work as needed to get the result. A good example is
http://dlang.org/phobos/std_range.html#take , which sets a
limit to the number of items to be used from the input.
So you can have an infinite random number generator, but only
take the first 50 numbers like so: randomGen.take(50);

By the way File("myfile").byLine() gives you a range over the
lines of text of "myfile". That's quite handy if you have an
array of strings like a dictionary in a text file.

-- 
Marco



More information about the Digitalmars-d-learn mailing list