Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I turn the Result type into something useful?

Tags:

range

d

I wanted a list of numbers:

auto nums = iota(0, 5000);

Now nums is of type Result. It cannot be cast to int[], and it cannot be used as a drop-in replacement for int[].

It's not very clear from the docs how to actually use an iota as a range. Am I using the wrong function? What's the way to make a "range" in D?

like image 775
cat Avatar asked Dec 18 '22 18:12

cat


1 Answers

iota, like many functions in Phobos, is lazy. Result is a promise to give you what you need when you need it but no value is actually computed yet. You can pass it to a foreach statement for example like so:

import std.range: iota;
foreach (i ; iota(0, 5000)) {
    writeln(i);
}

You don't need it for a simple foreach though:

foreach (i ; 0..5000) {
    writeln(i);
}

That aside, it is hopefully clear that iota is useful by itself. Being lazy also allows for costless chaining of transformations:

/* values are computed only once in writeln */
iota(5).map!(x => x*3).writeln;
// [0, 3, 6, 9, 12]

If you need a "real" list of values use array from std.array to delazify it:

int[] myArray = iota(0, 5000).array;

As a side note, be warned that the word range has a specific meaning in D that isn't "range of numbers" but describes a model of iterators much like generators in python. iota is a range (so an iterator) that produced a range (common meaning) of numbers.

like image 107
cym13 Avatar answered Jan 05 '23 10:01

cym13