How to generate an array with random values, without using a loop?

后端 未结 24 2106
逝去的感伤
逝去的感伤 2020-12-13 19:23

How can I generate an array in Perl with 100 random values, without using a loop?

I have to avoid all kind of loops, like \"for\", foreach\", while. This is my exerc

24条回答
  •  执笔经年
    2020-12-13 19:52

    map is used here as a topicalizer over a single value, exempting it from loop status:

    my @rand = map&$_($_),sub{@_<=100&&goto&{push@_,rand;$_[0]};shift;@_};
    

    or with two subs:

    my @rand = sub{&{$_[0]}}->(sub{@_<=100&&goto&{(@_=(rand,@_))[-1]};pop;@_});
    

    both of these are Y-combinator style self-passed subs that build up the list via iteration but one is clearly faster than the other.

    you can fix the inefficiency with s'g[^}]+'goto&{unshift@_,rand;$_[-1]' but then its getting a bit long.

    or to sidestep the call stack:

    my @rand = do{local*_=sub{(push@_,rand)<100?goto&_:@_};&_};
    

    or with eval, no variable assignment, no external state, one anon sub:

    my @rand = eval'sub{@_<100?eval((caller 1)[6]):@_}->(@_,rand)';
    

    but most concise of all is:

    my @rand = map&$_,sub{(100^push@_,rand)?goto&$_:@_};
    

提交回复
热议问题