Keep It Simple, Stupid PerlMonks

fun with induce

by daxim (Chaplain)
 on May 10, 2017 at 06:34 UTC ( #1189976=CUFP: print w/replies, xml ) Need Help??

```use Kavorka qw(fun);
use Scalar::Induce qw(induce void);

fun repeat(\$val!, \$times!) {
induce { \$_-- ? \$val : void undef \$_ } \$times;
}
repeat('foo', 5);
# ('foo', 'foo', 'foo', 'foo', 'foo')
repeat({bar => 42}, 3);
# 0  HASH(0x138be78)
#    bar => 42
# 1  HASH(0x138be78)
# 2  HASH(0x138be78)

fun range(:\$from = 1, :\$to!, :\$step = 1) {
induce {
my \$curr = \$_;
undef \$_ if (\$_ += \$step) > \$to;
return \$curr;
} \$from;
}
range(step => 1.1, from => 4, to => 17);
# (4, 5.1, 6.2, 7.3, 8.4, 9.5, 10.6, 11.7, 12.8, 13.9, 15, 16.1)
range(to => 7);
# (1, 2, 3, 4, 5, 6, 7)

fun partition(\$n!, @l!) {
induce {
my @part = splice @\$_, 0, \$n;
undef \$_ unless @\$_;
return \@part;
} \@l
}
partition(3, qw(Aragorn Boromir Frodo Gandalf Gimli Legolas Merry Pipp
+in Sam));
# (
#     ['Aragorn', 'Boromir', 'Frodo'],
#     ['Gandalf', 'Gimli', 'Legolas'],
#     ['Merry', 'Pippin', 'Sam']
# )

fun factor(\$n!) {
induce {
for my \$i (2..\$_/2) {
unless (\$_ % \$i) {
\$_ /= \$i;
return \$i;
}
}
my \$curr = \$_;
undef \$_;
return \$curr;
} \$n
}
factor(138600); # (2, 2, 2, 3, 3, 5, 7, 11)

Replies are listed 'Best First'.
Re: fun with induce
by no_slogan (Deacon) on May 10, 2017 at 13:45 UTC
Looks like Kavorka hasn't worked since 5.20, so that's certainly "fun." Let's add more fun.
```        for my \$i (2..\$_/2) {
=>
for my \$i (2..sqrt) {

Create A New User
Node Status?
node history
Node Type: CUFP [id://1189976]
Approved by LanX
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (11)
As of 2018-04-26 18:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My travels bear the most uncanny semblance to ...

Results (97 votes). Check out past polls.

Notices?