compiler error when trying to get random key from AA

Basile B. b2.temp at gmx.com
Sat Jan 25 09:18:01 UTC 2020


On Saturday, 25 January 2020 at 08:35:18 UTC, mark wrote:
> I have this code:
>
> import std.random;
> import std.stdio;
> void main()
> {
>     auto aa = ["one": 1, "two": 2, "three": 3];
>     writeln(aa);
>     auto rnd = rndGen;
>     auto word = aa.byKey.choice(rnd);
>     writeln(word);
> }
>
> And in the D playground it gives this error:
>
> onlineapp.d(8): Error: template std.random.choice cannot deduce 
> function from argument types !()(Result, 
> MersenneTwisterEngine!(uint, 32LU, 624LU, 397LU, 31LU, 
> 2567483615u, 11LU, 4294967295u, 7LU, 2636928640u, 15LU, 
> 4022730752u, 18LU, 1812433253u)), candidates are:
> /dlang/dmd/linux/bin64/../../src/phobos/std/random.d(2599):
>  choice(Range, RandomGen = Random)(auto ref Range range, ref 
> RandomGen urng)
>   with Range = Result,
>        RandomGen = MersenneTwisterEngine!(uint, 32LU, 624LU, 
> 397LU, 31LU, 2567483615u, 11LU, 4294967295u, 7LU, 2636928640u, 
> 15LU, 4022730752u, 18LU, 1812433253u)
>   must satisfy the following constraint:
>        isRandomAccessRange!Range
> /dlang/dmd/linux/bin64/../../src/phobos/std/random.d(2609):
>  choice(Range)(auto ref Range range)
>
> I am treating aa as a set and want to pick a random word from 
> it.
> What am I doing wrong?
>
> I'm sorry I can't give a link to this code in the D playground 
> but the URL in the web browser is just https://run.dlang.io/ 
> and when I click Shorten to get a URL nothing seems to happen 
> (using Firefox on Linux).

So the problem is that byKey is not a ref parameter, so you can 
use array on it:

---
import std.random;
import std.stdio;
import std.array;
void main()
{
     auto aa = ["one": 1, "two": 2, "three": 3];
     writeln(aa);
     Random rnd;
     auto word = choice(aa.byKey.array, rnd);
     writeln(word);
}
---

sorry for the previous noise.


More information about the Digitalmars-d-learn mailing list