<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Simon Proctor</title>
    <description>The latest articles on DEV Community by Simon Proctor (@scimon).</description>
    <link>https://dev.to/scimon</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F53081%2F09f2de29-685c-4495-9bc5-a6d74a7b696e.jpeg</url>
      <title>DEV Community: Simon Proctor</title>
      <link>https://dev.to/scimon</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/scimon"/>
    <language>en</language>
    <item>
      <title>I like things to be easy</title>
      <dc:creator>Simon Proctor</dc:creator>
      <pubDate>Thu, 14 Apr 2022 12:15:28 +0000</pubDate>
      <link>https://dev.to/scimon/i-like-things-to-be-easy-4pfh</link>
      <guid>https://dev.to/scimon/i-like-things-to-be-easy-4pfh</guid>
      <description>&lt;h2&gt;
  
  
  The Situation
&lt;/h2&gt;

&lt;p&gt;You've got a &lt;em&gt;large&lt;/em&gt; JSON file, in my case 21MB, that takes a while to parse. You want to have a web service running that can load this file into memory and server data from it. Nice and simple right? Sure the initial data read might take a few seconds but after that the service can just trundle along.&lt;/p&gt;

&lt;p&gt;Here's a simple example using &lt;a href="https://cro.services/"&gt;Cro&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use JSON::Fast;
use Cro::HTTP::Router;
use Cro::HTTP::Server;

constant DATAFILE = 'data.json';
my $data = from-json($data)

my $application = route {
    get -&amp;gt; 'count' {
        content 'text/plain', "{$data.keys.elems}\n";
    }
    get -&amp;gt; 'keys' {
        content 'text/plain', "{$data.keys.join(",")}\n";
    }
    get -&amp;gt; $uid {
        not-found unless $data{$uid}:exists;
        content 'text/plain', "{$data{$uid}.keys.join(",")}\n";
    }
    get -&amp;gt; $uid, $cid {
        not-found unless ($data{$uid}:exists) &amp;amp;&amp;amp; ($data{$uid}{$cid}:exists);
        content 'text/plain', "{$data{$uid}{$cid}}\n";
    }
}

my Cro::Service $server = Cro::HTTP::Server.new:
    :host&amp;lt;localhost&amp;gt;, :port&amp;lt;5000&amp;gt;, :$application;

$server.start;
react whenever signal(SIGINT) {
    $server.stop;
    exit;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(Most of this is cribbed from the Cro docs to be honest.)&lt;/p&gt;

&lt;p&gt;&lt;code&gt;$data&lt;/code&gt; is read at the start and then shared between our threads. (Note it's a two level data structure but that's not that important for the example). The data is immutable and everything is fine.&lt;/p&gt;

&lt;h2&gt;
  
  
  The wrinkle
&lt;/h2&gt;

&lt;p&gt;Every once in a while the data file gets updated. When this happens we have a bunch of rules we need to apply :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;it's OK for a request to server stale data for a bit&lt;/li&gt;
&lt;li&gt;request should return in a timely fashion (so no 3 second waits to read our data file allowed)&lt;/li&gt;
&lt;li&gt;the server should always serve response (so we can't just reboot the server).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now we could fire up a new server and swap them in a proxying system, that wouldn't be too hard. But what if we could hot swap the &lt;em&gt;data&lt;/em&gt; and keep the server running?&lt;/p&gt;

&lt;h2&gt;
  
  
  A solution
&lt;/h2&gt;

&lt;p&gt;It might not be &lt;em&gt;the&lt;/em&gt; solution, feel free to comment with others but here's what I came up with.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;unit class JSONDataWatcher;

use JSON::Fast;

subset DataFilePath of Str:D where *.IO:e &amp;amp;&amp;amp; *.IO.f;

has DataFilePath $!datafile;
has $.data;
has Lock $!lock;

method !update-data {
    my $read;
    try {
        $read = from-json( $!datafile.IO.slurp );
    }
    $!lock.protect( {$!data = $read} ) unless $!;
}

submethod BUILD( DataFilePath:D :$!datafile ) {
    $!lock = Lock.new();
    self!update-data();
    start react {
        whenever $!datafile.IO.watch() {
           self!update-data();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here was have a JSONDataWatcher class. You give it a file path and it does a couple of things :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Parses the JSON file and puts it in it's $.data value&lt;/li&gt;
&lt;li&gt;Sets up a watcher on the file path if the file changes it tries to reload and update the data.

&lt;ul&gt;
&lt;li&gt;If the data parsing fails (which if the file hasn't finished being written could well happen) we ignore it and keep using the old data&lt;/li&gt;
&lt;li&gt;If it parses OK we lock the data attribute while we update it. This will give us a small blip when doing reads but I figure it's safer.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Then we can update our server so :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use JSONDataWatcher;
use Cro::HTTP::Router;
use Cro::HTTP::Server;

constant DATAFILE = 'data.json';
my $w = JSONDataWatcher( datafile =&amp;gt; DATAFILE );

my $application = route {
    get -&amp;gt; 'count' {
        content 'text/plain', "{$w.data.keys.elems}\n";
    }
    get -&amp;gt; 'keys' {
        content 'text/plain', "{$w.data.keys.join(",")}\n";
    }
    get -&amp;gt; $uid {
        not-found unless $w.data{$uid}:exists;
        content 'text/plain', "{$w.data{$uid}.keys.join(",")}\n";
    }
    get -&amp;gt; $uid, $cid {
        not-found unless ($w.data{$uid}:exists) &amp;amp;&amp;amp; ($data{$uid}{$cid}:exists);
        content 'text/plain', "{$w.data{$uid}{$cid}}\n";
    }
}

my Cro::Service $server = Cro::HTTP::Server.new:
    :host&amp;lt;localhost&amp;gt;, :port&amp;lt;5000&amp;gt;, :$application;

$server.start;
react whenever signal(SIGINT) {
    $server.stop;
    exit;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Notes
&lt;/h2&gt;

&lt;p&gt;This is all a bit rough and ready, there's some error checking I'd add. But I thought it would be interesting to show what you can do with &lt;a href="https://raku.org/"&gt;Raku&lt;/a&gt;. Note that apart from the data parsing everything in the &lt;code&gt;JSONDataWatcher&lt;/code&gt; class is core to the language.&lt;/p&gt;

&lt;p&gt;Enjoy and stay safe.&lt;/p&gt;

</description>
      <category>raku</category>
      <category>rakulang</category>
      <category>json</category>
    </item>
    <item>
      <title>The Weekly Challenge : Week 133 in Raku</title>
      <dc:creator>Simon Proctor</dc:creator>
      <pubDate>Fri, 08 Oct 2021 13:16:55 +0000</pubDate>
      <link>https://dev.to/scimon/the-weekly-challenge-week-133-in-raku-2epc</link>
      <guid>https://dev.to/scimon/the-weekly-challenge-week-133-in-raku-2epc</guid>
      <description>&lt;h2&gt;
  
  
  Back to the Challenges
&lt;/h2&gt;

&lt;p&gt;So it's been a while since I blogged about the &lt;a href="https://theweeklychallenge.org/"&gt;Weekly Challenges&lt;/a&gt;. Heck I've been a bit up and down due to everything going on and haven't even done them every week. &lt;/p&gt;

&lt;p&gt;But I'm back on the wagon off to the races or something, so lets look at this weeks challenges.&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;a href="https://theweeklychallenge.org/blog/perl-weekly-challenge-133/#TASK1"&gt;Challenge 1&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;Now Raku doesn't have a &lt;code&gt;isqrt&lt;/code&gt; functions built in and the challenge states not to &lt;em&gt;use&lt;/em&gt; built in functions. Still if we &lt;em&gt;were&lt;/em&gt; allowed it it's pretty simple.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sub isqrt( UInt \n ) { \n.sqrt.Int() }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Cue discussion in &lt;a href="https://www.reddit.com/r/rakulang/"&gt;/r/rakulang&lt;/a&gt; about which method I &lt;em&gt;should&lt;/em&gt; have used to round the value off. It's beside the point for the case in point because we're here to talk about how to calculate it &lt;em&gt;without&lt;/em&gt; using built in functions.&lt;/p&gt;

&lt;p&gt;One thing to note, on my laptop doing &lt;code&gt;iqsrt(999999999999999)&lt;/code&gt; using that method takes about 0.14 seconds. &lt;/p&gt;

&lt;p&gt;So there's lots of Maths on Wikipedia dealing with calculating integer square roots but as is my wont I figured lets try something simple. Count from 1 to Infinity until I find a number that when squared is bigger than the number I'm looking for. The number &lt;em&gt;before&lt;/em&gt; it will be the integer square root. &lt;/p&gt;

&lt;p&gt;Sure for a human that's insanely tedious but doing insanely tedious counting is what we invented computers for. Here's the code for that :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sub isqrt(UInt \n) {
    (1..*).first( { $_ * $_ &amp;gt; n } ) - 1;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So... make the &lt;a href="https://docs.raku.org/type/Range"&gt;Range&lt;/a&gt; 1 to Infinity (here denoted by a &lt;code&gt;*&lt;/code&gt; but I could use the &lt;code&gt;∞&lt;/code&gt; symbol if I wanted. I tend to not use Unicode much though as it's a pain to type) and find the &lt;a href="https://docs.raku.org/routine/first"&gt;first&lt;/a&gt; value that when squared is bigger that the target. (I love first it's like &lt;a href="https://docs.raku.org/routine/grep"&gt;grep&lt;/a&gt; but when you just want the first thing. Then we just subtract one and return. Simples.&lt;/p&gt;

&lt;p&gt;(And yes &lt;code&gt;$_²&lt;/code&gt; or &lt;code&gt;$_ ** 2&lt;/code&gt; would work too... but... does it make a huge difference? I don't think so.)&lt;/p&gt;

&lt;p&gt;And there we go. Interesting thing to note if you time &lt;code&gt;iqsrt(999999999999999)&lt;/code&gt; using this method it's about .2s. Not too bad (though... it's not a linear progression... add 5 more 9's and it's slows to just over a second).&lt;/p&gt;

&lt;p&gt;Another method I saw was to use a &lt;a href="https://docs.raku.org/type/Sequence"&gt;Sequence&lt;/a&gt; with the check in the terminator, something like this :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sub isqrt(UInt \n) {
    (1...*² &amp;gt; n)[*-2]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;(See I can use fancy unicode stuff if I want to). And that works except... it takes over 1 second to calculate &lt;code&gt;iqsrt(999999999999999)&lt;/code&gt; and for 15 9's I get bored waiting. (I do get bored easily though).&lt;/p&gt;

&lt;p&gt;So... yeah, Sequences are fun but a whole bunch slower than a Range. &lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;a href="https://theweeklychallenge.org/blog/perl-weekly-challenge-133/#TASK2"&gt;Challenge 2&lt;/a&gt;
&lt;/h3&gt;

&lt;p&gt;So this challenges is about Smith Numbers and a quick look at the Wikipedia page we see that we need prime factors. Luckily if you've been doing the Weekly challenge (almost every week...) then this is not your prime factor rodeo. &lt;a href="https://theweeklychallenge.org/blog/perl-weekly-challenge-041/"&gt;Challenge 41&lt;/a&gt; required to find prime factors so a quick duck into the archives and I find this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use experimental :cached;

sub prime-factors( Int $n is copy --&amp;gt; Array ) is pure {
    my @factors;
    while ! $n.is-prime {
        my \s = smallest-factor( $n );
        @factors.push(s);
        $n = $n div s;
    }
    @factors.push($n);
    return @factors;
}

sub smallest-factor( Int \n --&amp;gt; Int ) is pure is cached {
    for (2..(n div 2)).grep(*.is-prime) {
        return $_ if n %% $_;
    }
    die "Something went wrong";
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So here we do recursive sub division of a number to find the smallest prime factor and put them into a list. (This is made a lot easier by &lt;a href="https://docs.raku.org/routine/is-prime"&gt;is-prime&lt;/a&gt; and &lt;a href="https://docs.raku.org/routine/%24PERCENT_SIGN%24PERCENT_SIGN"&gt;%%&lt;/a&gt;. So now we want to find the Smith numbers, specifically the first ten. In my (get computers to count lots for you) way I figure this is a job for a Range and grep!&lt;/p&gt;

&lt;p&gt;Generally I find many things I attempt are a job for map, grep and reduce.&lt;/p&gt;

&lt;p&gt;So here's our Main sub:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sub MAIN ( UInt \n = 10 ) {
    .say for (2..*).grep( { is-smith-number($_) } )[^n];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Simple right...&lt;/p&gt;

&lt;p&gt;...&lt;/p&gt;

&lt;p&gt;Oh... you want to see what &lt;code&gt;is-smith-number&lt;/code&gt; has in it. Well there are two possibilities. Firstly the number is prime in which case it's not a Smith number so that's simple :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;multi sub is-smith-number( Int \n where n.is-prime --&amp;gt; False ) {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here I'm using a trick I picked up for this sort of case to put the return directly into the signature which feels &lt;em&gt;Rakuish&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;And then there's the case where it isn't prime. Here we sum the values of the number and for each factor sum the sum of each value... Look here's the code hopefully it will make sense :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;multi sub is-smith-number( Int \n --&amp;gt; Bool ) is pure {
    my @factors = prime-factors( n );
    ([+] n.comb) == ([+] @factors.map( { [+] $_.comb } ));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;[+] $var.comb&lt;/code&gt; casts a number to a string and then splits it it's individual values and then does a recursive addition to get the sum. If the sun of the values equals the sum of the sum of the values of each factor then it's a Smith number.&lt;/p&gt;

&lt;p&gt;As I mentioned timings before that takes about 0.3s to calculate the first 10 Smith Numbers (and 0.5s for the first 100). Once the &lt;code&gt;new-disp&lt;/code&gt; branch has been released as stable I'll maybe run it again and see if it changes at all (the &lt;code&gt;multi&lt;/code&gt; call should hopefully be a bit faster).&lt;/p&gt;

&lt;p&gt;Anyway, there we go, enjoy the challenge, hopefully I'll write more next week. &lt;/p&gt;

</description>
      <category>raku</category>
      <category>weeklychallenge</category>
    </item>
    <item>
      <title>Why not reduction?</title>
      <dc:creator>Simon Proctor</dc:creator>
      <pubDate>Thu, 30 Sep 2021 14:11:27 +0000</pubDate>
      <link>https://dev.to/scimon/why-not-reduction-5fob</link>
      <guid>https://dev.to/scimon/why-not-reduction-5fob</guid>
      <description>&lt;p&gt;So it's been a while since I posted here but a post on the &lt;a href="https://theweeklychallenge.org/blog/perl-weekly-challenge-131/#TASK1"&gt;Weekly Challenge number 131&lt;/a&gt; made me want to share my solution. The &lt;a href="https://gfldex.wordpress.com/2021/09/24/convolution/"&gt;blog post by glfdex&lt;/a&gt; was inspired by &lt;a href="https://github.polettix.it/ETOOBUSY/2021/09/22/pwc131-consecutive-arrays/"&gt;this one by Falvio&lt;/a&gt;. Anyway I looked at both of these and wondered... "Why didn't they use reduction?"&lt;/p&gt;

&lt;h2&gt;
  
  
  An Aside
&lt;/h2&gt;

&lt;p&gt;For those of you who don't know, reduction is one of the core list processing utilities. I tend to use it alot in the form of the &lt;a href="https://docs.raku.org/language/operators#index-entry-%5B%5D_(reduction_metaoperators)"&gt;Reduction Meta operator&lt;/a&gt; which works something like this. &lt;/p&gt;

&lt;p&gt;Given a list a,b,c,d,e apply the operation to a and b, then apply the operation to the result of that and C and so one. So an example :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;say [+] 1,2,3,4,5,6
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;is the same as writing :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;say (((((1+2)+3)+4)+5)+6)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;but as well as the reduction operator Raku also has the &lt;a href="https://docs.raku.org/routine/reduce"&gt;reduce method&lt;/a&gt; which takes a pair of inputs and returns a single result.&lt;/p&gt;

&lt;h2&gt;
  
  
  Back to the challenge
&lt;/h2&gt;

&lt;p&gt;So I want to use &lt;code&gt;reduce&lt;/code&gt; to solve this. Lets start with a simple wrapper :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sub MAIN( *@vals where *.all ~~ Int() ) {
    @vals.reduce(
        ... # Insert reduction here
    ).say;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So if we want to use reduce we want it to return an Array of Arrays, but this means our reduction is going to receive such an array for it's first value. But not at the start of the list... Still that's not too hard to deal with.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sub MAIN( *@vals where *.all ~~ Int() ) {
    @vals.reduce(
        -&amp;gt; $v1 is copy, $v2 {
            if $v1 ~~ Int(Str) {
                $v1 = [[$v1],]
            }
            ...
            $v1
        }
    ).say;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we make our first value a copy so we can modify it (other wise it's immutable, which is good generally). If it's an Integer (or more generally an IntStr allomorph) we turn it into an Array with a single element (an Array containing the value). We need the trailing comma there or we fall foul to the &lt;a href="https://docs.raku.org/language/list#index-entry-Single_Argument_Rule"&gt;single argument rule&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now we can do the bulk of our code. Which is pretty simple really. If &lt;code&gt;$v2&lt;/code&gt; is equal to 1 more than the last item in the last array in $v1 which append it to the list. Otherwise we append a new array containing &lt;code&gt;$v2&lt;/code&gt;.... that was simple right... Look here's the code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sub MAIN( *@vals where *.all ~~ Int() ) {
    @vals.reduce(
        -&amp;gt; $v1 is copy, $v2 {
            if $v1 ~~ Int(Str) {
                $v1 = [[$v1],]
            }
            if $v1[*-1][*-1] ~~ $v2-1 {
                $v1[*-1].push($v2)
            } else {
                $v1.push( [ $v2, ] )
            }
            $v1
        }
    ).say;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And there we go. A nice simple reduction that goes through the list... But looking at it I think it can be better. Really we don't want to be copying and pushing to lists, that &lt;em&gt;reduces&lt;/em&gt; our ability to split it into multiple jobs. Which isn't an issue with a few items but what if we had a list of 100,000? Wouldn't it be nice to just add a &lt;code&gt;hyper&lt;/code&gt; and let all our cores do something with it?&lt;/p&gt;

&lt;p&gt;... So I did a bit of experimenting and it doesn't play as nice with hyper as I hoped but here's a more purely functional version of the reduction.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sub group-vals (@vals) {
    return lazy @vals.map( { (($_,),) } ).reduce(&amp;amp;join-list);
}

sub join-list( \l1, \l2 ) {
    if ( l1[*-1][*-1]+1 ~~ l2[0][0] ) {
        (
            |(l1.elems &amp;gt; 1 ?? l1[0..^*-1] !! Empty),
            (|l1[*-1], |l2[0],),
            |(l2.elems &amp;gt; 1 ?? l2[1..*] !! Empty )
        );
    } else {
        (|l1, |l2);
    }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So firstly we assume that the caller handles the printing and instead return a lazy list (so if we don't need all of it we can skip it). Then we make our list into a list of lists and now we can reduce it.&lt;/p&gt;

&lt;p&gt;Our reduction now takes two lists of lists. We either want to join them or not depending on the items at the end and start of each. For example :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;((1,2),(3)) and ((4))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here the 3 and 4 are in sequence so we join them into :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;((1,2),(3,4))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note that this code can handle if the second list is longer than a single character. So I think for big lists (up to 10,000 hyper does fine) I need to break it into small lists and reduce each of them then do a second final reduction on the result. &lt;/p&gt;

&lt;p&gt;Anyway.... that how I handled it. Enjoy.&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Weekly Challenge in Raku : Week 79 Retrospective</title>
      <dc:creator>Simon Proctor</dc:creator>
      <pubDate>Wed, 30 Sep 2020 13:09:14 +0000</pubDate>
      <link>https://dev.to/scimon/weekly-challenge-in-raku-week-79-retrospective-4bg6</link>
      <guid>https://dev.to/scimon/weekly-challenge-in-raku-week-79-retrospective-4bg6</guid>
      <description>&lt;h1&gt;
  
  
  Is this thing on?
&lt;/h1&gt;

&lt;p&gt;With everything going on in the world I've been finding it hard to write stuff. But today the &lt;a href="https://perlweeklychallenge.org/blog/p6-review-challenge-079/"&gt;review of Week 79 of the weekly challenge&lt;/a&gt; was released. Andrew does an amazing job of going over the various Raku challenges and I've got to admit I love watching him &lt;a href="https://www.youtube.com/watch?v=1vnhtIiWkjo&amp;amp;t=1223s"&gt;go over my code&lt;/a&gt;. It's always good (and often nice) to see how other people react to your code. As a developer I have my code reviewed often and having it done in video is just great. &lt;/p&gt;

&lt;p&gt;Watching the review I realised that I'd got into a situation I often get into which is latching onto a solution and not considering others. Firstly you need to bear in mind &lt;a href="https://perlweeklychallenge.org/blog/perl-weekly-challenge-075/"&gt;Challenge 75&lt;/a&gt; which also involved histograms and I quite liked my code I wrote to draw them for that challenge.&lt;/p&gt;

&lt;p&gt;(It is I know a bit over the top, I got a bit into my functional programming weeds there). But anyway, because I already had code to draw a histogram I figured I'd reuse that and repurpose it for this challenge.&lt;/p&gt;

&lt;h1&gt;
  
  
  The perils of cut and paste.
&lt;/h1&gt;

&lt;p&gt;Cut and paste programming has lots going for it, it lets you get moving when a blank screen can leave you pulling out your hair. But it's also terrible for sending you down paths because of the ideas employed in the original code.&lt;/p&gt;

&lt;p&gt;In this case I got caught up on the idea of calculating the area of a rectangle. &lt;/p&gt;

&lt;h2&gt;
  
  
  A simple example
&lt;/h2&gt;

&lt;p&gt;Take the array of heights &lt;code&gt;3,0,0,0,3&lt;/code&gt; this gives this histogram. (We assume there is a floor and water doesn't fall out the bottom).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#   #     #~~~#
#   #  =&amp;gt; #~~~#
#   #     #~~~#
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we can see this has 9 squares of rain water and the area calculation is the width times the height or &lt;code&gt;3 x 3 = 9&lt;/code&gt; nice and simple. (At this point I've started down the path which takes me all kinds of fun place).&lt;/p&gt;

&lt;h2&gt;
  
  
  Adding a floor
&lt;/h2&gt;

&lt;p&gt;Of course generally all our heights are greater than 0 giving us a nice floor so here's another simple array &lt;code&gt;3,1,1,1,3&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#   #     #~~~#
#   #  =&amp;gt; #~~~#
#####     #####
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here are area is 6, the calculation for this is the width inside (3) times the height of the edges (3) minus the sum of the internal heights (1+1+1). Giving us &lt;code&gt;(3 x 3) - (1+1+1) = 6&lt;/code&gt;. Of course this is still a simple example. &lt;/p&gt;

&lt;p&gt;(Note that this calculation still holds true for our original case it's just the internal heights sum up to 0).&lt;/p&gt;

&lt;h2&gt;
  
  
  Complication 1 : Different edge heights
&lt;/h2&gt;

&lt;p&gt;So I'm still trundling along with my plan, it's making sense so far. But what if out edges have different heights? Lets try &lt;code&gt;5,1,1,1,3&lt;/code&gt; and what do we get?&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#         #
#         #
#   #  =&amp;gt; #~~~#
#   #     #~~~#
#####     #####
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Still 6 squares and it's easy to see our algorithm still works. We just use the height of the smaller edge for the height of the area. &lt;code&gt;(3 x 3) - (1+1+1) = 6&lt;/code&gt; nice and easy. At this point I felt I was on a winner.&lt;/p&gt;

&lt;h2&gt;
  
  
  Complication 2 : Rough ground
&lt;/h2&gt;

&lt;p&gt;What if the floor isn't nice and smooth? Lets give this array a shot &lt;code&gt;4,1,2,1,3,4&lt;/code&gt; and see :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#   #     #~~~#
#  ##  =&amp;gt; #~~##
# ###     #~###
#####     #####
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So our algorithm gives us a height of &lt;code&gt;4&lt;/code&gt; and a width of &lt;code&gt;3&lt;/code&gt; and inner heights of &lt;code&gt;1+2+3 = 6&lt;/code&gt; so this comes to &lt;code&gt;(4 x 3) - 6 = 6&lt;/code&gt; and as we can see that's right.&lt;/p&gt;

&lt;p&gt;So at this point I'm feeling pretty awesome... of course here's where it starts to fall apart. &lt;/p&gt;

&lt;h2&gt;
  
  
  The centre cannot hold
&lt;/h2&gt;

&lt;p&gt;What if there's a spike in the middle? A point higher than the edges? Like &lt;code&gt;3,1,4,1,3&lt;/code&gt; :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  #         #
# # #  =&amp;gt; #~#~#
# # #     #~#~#
#####     #####
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So our algorithm is going to get the smallest edge &lt;code&gt;3&lt;/code&gt; and the width &lt;code&gt;3&lt;/code&gt; and the internal heights &lt;code&gt;1+4+1 = 6&lt;/code&gt; and we get &lt;code&gt;(3 x 3) - 6 = 3&lt;/code&gt;... And that's wrong. &lt;/p&gt;

&lt;p&gt;So here is where I probably should have taken a step back and wondered if there was a better way, but I was on a roll. Simple change to the algorithm now when summing the height was count either the height in the array or our minimum side height whichever is smaller.&lt;/p&gt;

&lt;p&gt;This is a warning note really, if your simple algorithm is starting to have extra checks in it then you're maybe going the wrong way. It's also a warning that's really easy to spot in hindsight.&lt;/p&gt;

&lt;p&gt;Anyway with that in place we now have &lt;code&gt;(3 x 3) - (1 + 3 + 1) = 4&lt;/code&gt; and we're done!&lt;/p&gt;

&lt;p&gt;I actually thought I was finished at this point. I messed around with a few more arrays and then.... oh boy.&lt;/p&gt;

&lt;h2&gt;
  
  
  The slope to heck
&lt;/h2&gt;

&lt;p&gt;Lets try something else I mean we've got an awesome algorithm right? &lt;code&gt;1,2,5,1,4&lt;/code&gt; should look good.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  #        #
  # #      #~#
  # # =&amp;gt;   #~#
 ## #     ##~#
#####    #####
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this point the algorithm completely collapses giving &lt;code&gt;(1 x 3) - (1+1+1) = 0&lt;/code&gt;. &lt;/p&gt;

&lt;h1&gt;
  
  
  Step away from the keyboard
&lt;/h1&gt;

&lt;p&gt;There are moments when you need to step back. Which I did but... not that far back. See the algorithm worked for a lot of cases looking at this one I could see it could be considered 2 separate arrays.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  #        #   #
  # #      #   #~#
  # # =&amp;gt;   # + #~#
 ## #     ##   #~#
#####    ###   ###
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;1,2,5&lt;/code&gt; and &lt;code&gt;5,1,4&lt;/code&gt; with that we get two passes of the algorithm for the first we have a height of &lt;code&gt;1&lt;/code&gt; a width of &lt;code&gt;1&lt;/code&gt; and internal height of &lt;code&gt;1&lt;/code&gt; so &lt;code&gt;(1 x 1) - 1 = 0&lt;/code&gt;. Meanwhile we have in the second array we have a height of &lt;code&gt;4&lt;/code&gt; a width of &lt;code&gt;1&lt;/code&gt; and and internal height total of &lt;code&gt;1&lt;/code&gt; so &lt;code&gt;(4 x 1) - 1 = 3&lt;/code&gt; add those up and you get 3. So the algorithm works from discrete chunks of the map. &lt;/p&gt;

&lt;p&gt;At this point the functional programmer in me is reaching for the recursion hat. Raku &lt;code&gt;multi&lt;/code&gt; method make it really  easy to do a recursive function like this so in the end I found 3 cases :&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;There is a spike taller than the edges in the centre section 

&lt;ul&gt;
&lt;li&gt;In this case we want to split our array into two sub arrays and check each of them&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;There is only 1 or two items in the array

&lt;ul&gt;
&lt;li&gt;In that case we always return nothing, there will be no rain fall. This is the case that Andrew didn't spot in the review.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;The two edges are the highest possible and there is at least 1 space in between

&lt;ul&gt;
&lt;li&gt;Calculate the area using our simple algorithm&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The code for this is as follows : &lt;/p&gt;

&lt;p&gt;Firstly case 1. Where there is a spike inside a heights array. Note we pass an offset so the drawing code knows where this water is.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;multi sub calculate-rain-levels( 
  @heights where { 
    any(@heights[0^..^*-1]) &amp;gt; any(@heights[0],@heights[*-1])  
  }, 
  $offset = 0
) {
  my $max = max(@heights[0^..^*-1]);
  # This is a bad name... it's really the first
  # Index of a height greater than the edges. 
  my $mid-idx = @heights[0^..^*-1].kv.map( 
    -&amp;gt; $k, $v { $v == $max ?? $k+1 !! Empty } )[0];

  # As calculate-rain-levels returns an array we slip it so
  # we don't end up with nested array.
  return ( 
    |calculate-rain-levels( @heights[0..$mid-idx],$offset ),
    |calculate-rain-levels( @heights[$mid-idx..*],$mid-idx+$offset ) 
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Case 3. Here we match again and were only accepting arrays with 3 or more values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;multi sub calculate-rain-levels( 
  @heights where { @heights.elems &amp;gt; 2 }, 
  $offset=0 
) {
  # Here is our simplified algorithm
  # Get the highest edge
  my $height = min( @heights[0], @heights[*-1] );
  # Area = height * width on the inside
  my $area = $height * ( @heights.elems - 2 );
  # Then remove the floors, no need to check the height.
  $area -= [+] @heights[0^..^*-1];
  # RainArea is a data transfer object that is used by the
  # drawing system
  return RainArea.new( 
    range =&amp;gt; ( $offset..^($offset+@heights.elems) ), 
    :$area, 
    :$height 
  ); 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Case 2 (one or two items) is now the fallback case where we just want to return nothing. We use anonymous variables in the signature because we don't care about them&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;multi sub calculate-rain-levels(@,$) { Empty }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h1&gt;
  
  
  And there we go.
&lt;/h1&gt;

&lt;p&gt;Hopefully this makes some sort of sense of the rambling thread of logic I followed to finish this challenge. Thanks again the Mohammad for all his work managing the challenge to Andrew for his Raku reviews and to everyone who takes part. I always enjoy Monday mornings brain teaser. &lt;/p&gt;

&lt;p&gt;Have fun all and be well in this difficult times. &lt;/p&gt;

</description>
      <category>raku</category>
    </item>
    <item>
      <title> The Weekly Challenge in Raku : Week 72 (Part 2) </title>
      <dc:creator>Simon Proctor</dc:creator>
      <pubDate>Tue, 04 Aug 2020 08:27:24 +0000</pubDate>
      <link>https://dev.to/scimon/the-weekly-challenge-in-raku-week-72-part-2-12oh</link>
      <guid>https://dev.to/scimon/the-weekly-challenge-in-raku-week-72-part-2-12oh</guid>
      <description>&lt;p&gt;So &lt;a href="https://dev.to/scimon/the-weekly-challenge-in-raku-week-72-part-1-2i0g"&gt;Part 1&lt;/a&gt; was interesting and I've got a final coda to that. Here's probably the smallest and fastest way to solve the challenge.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;unit sub MAIN( UInt $N where * &amp;lt;= 10 );
say '00000111112'.comb[$N];
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;...&lt;/p&gt;

&lt;p&gt;Yup. So lets break this down. First up the &lt;a href="https://docs.raku.org/syntax/unit"&gt;unit&lt;/a&gt; declarator says everything in the current file is part of the &lt;code&gt;MAIN&lt;/code&gt; sub. It's not really required but I liked it.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;'00000111112'.comb&lt;/code&gt; takes the string and splits it into a list. It's a bit shorter than writing the list with commas. Then we simply look up the index for &lt;code&gt;$N&lt;/code&gt; in the list. &lt;/p&gt;

&lt;p&gt;This works because of the restriction on &lt;code&gt;$N&lt;/code&gt; that it can't be greater than 10 so we can pre-calculate the results. This may seem like "cheating" but it's an important trick for a developer to have. Sometimes it's faster to pre-calculate and cache data than it to make it on the fly. &lt;/p&gt;

&lt;p&gt;Anyway onto the second task. &lt;/p&gt;

&lt;h2&gt;
  
  
  Task 2
&lt;/h2&gt;

&lt;p&gt;So for this one I'm just going to share my whole answer and then go over what it's doing : &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;subset FilePath of Str where *.IO:f;

#| Read and output lines A -&amp;gt; B in the given text file
sub MAIN (
    UInt $A where * &amp;gt; 0, #= Start line
    UInt $B where * &amp;gt;= $A, #= End line
    FilePath :f(:$file) = "test-file.txt", #= Text file to read
) {
    .say for $file.IO.lines[$A-1..$B-1];
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Yes. The answer is 1 line of code. Everything else is validating input values, this is my favourite kind of function. Especially when the input validation is not done inside the function.&lt;/p&gt;

&lt;p&gt;For the validation we firstly define a &lt;a href="https://docs.raku.org/language/typesystem#index-entry-subset-subset"&gt;subset&lt;/a&gt; of the Str type. Subsets are effectively named &lt;a href="https://docs.raku.org/type/Signature#index-entry-where_clause"&gt;where clauses&lt;/a&gt; which make the code easier to read and also make the computed Usage message nicer to read as well. &lt;/p&gt;

&lt;p&gt;The where clause casts our String to an IO object (treating it as a path) and then checks there's a file at that location. &lt;/p&gt;

&lt;p&gt;Note the UInt is a subset of Int and that as with &lt;code&gt;$A&lt;/code&gt; and &lt;code&gt;$B&lt;/code&gt; you can combine a subset and an additonal where clause. Also as in &lt;code&gt;$B&lt;/code&gt; you can reference other parameters in your where clauses.&lt;/p&gt;

&lt;p&gt;In all I love this signature for displaying the power of signatures in Raku it allows you to take a lot of the boiler plate for validation and shift it up, often allowing for compile time checking. &lt;/p&gt;

&lt;p&gt;And now the meat of the function. &lt;code&gt;$file.IO&lt;/code&gt; makes an &lt;a href="https://docs.raku.org/type/IO::Path"&gt;IO::Path&lt;/a&gt; object that points to the file we want to read. Then we call the &lt;a href="https://docs.raku.org/routine/lines#class_IO::Path"&gt;lines&lt;/a&gt; method to get a sequence that returns lines in the file. (This is evaluated lazily which is nice).&lt;/p&gt;

&lt;p&gt;Next we slice the sequence from &lt;code&gt;$A-1&lt;/code&gt; (as the challenge specifies indexing from 1 and Raku indexes from 0) to &lt;code&gt;$B-1&lt;/code&gt; and finally print each line with the &lt;code&gt;.say&lt;/code&gt; method. When you call &lt;code&gt;for&lt;/code&gt; and don't define the variable it uses &lt;code&gt;$_&lt;/code&gt; and when you call a method without an object you use &lt;code&gt;$_&lt;/code&gt; so bingo.&lt;/p&gt;

&lt;p&gt;One of the things I love about Raku is it's ability to make things that you need to do often really really simple. Leaving you time to focus on the interesting problems. &lt;/p&gt;

</description>
      <category>raku</category>
    </item>
    <item>
      <title>The Weekly Challenge in Raku : Week 72 (Part 1)</title>
      <dc:creator>Simon Proctor</dc:creator>
      <pubDate>Mon, 03 Aug 2020 13:15:44 +0000</pubDate>
      <link>https://dev.to/scimon/the-weekly-challenge-in-raku-week-72-part-1-2i0g</link>
      <guid>https://dev.to/scimon/the-weekly-challenge-in-raku-week-72-part-1-2i0g</guid>
      <description>&lt;p&gt;&lt;a href="https://perlweeklychallenge.org/blog/perl-weekly-challenge-072/"&gt;This weeks challenge&lt;/a&gt; is not going to be too taxing. There are a few fun little bits we can do though. &lt;/p&gt;

&lt;h2&gt;
  
  
  Part 1 : Trailing Zeros
&lt;/h2&gt;

&lt;p&gt;In this challenge we're to find the number of trailing Zero's in &lt;code&gt;$N!&lt;/code&gt; where &lt;code&gt;$N &amp;lt;= 10&lt;/code&gt; so really it's a two part challenge, find &lt;code&gt;$N!&lt;/code&gt; and count trailing zeros.&lt;/p&gt;

&lt;h3&gt;
  
  
  Finding Factorials
&lt;/h3&gt;

&lt;p&gt;First thing to note is we can define the &lt;code&gt;!&lt;/code&gt; factorial operator quite easily :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sub postfix:&amp;lt;!&amp;gt; (UInt $N) {...}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We'll cover the &lt;code&gt;...&lt;/code&gt; bit in a sec but this defines &lt;code&gt;!&lt;/code&gt; as a postfix operator that requires and Unsigned Integer in front of it. Thing is I won't be using this in my challenge because right now defining operators directly in scripts really slows down parsing (if you put them in Modules you get them precompiled but generally I don't make a module for the challenges). &lt;/p&gt;

&lt;p&gt;Still it's nice to know you can do it. Anyway lets say we instead make a &lt;code&gt;fact($N)&lt;/code&gt; sub how hard is that?&lt;/p&gt;

&lt;p&gt;Personally I can think of three different ways of doing it off the top of my head, all of which are quite &lt;em&gt;Rakuish&lt;/em&gt; so lets cover them each. &lt;/p&gt;

&lt;h3&gt;
  
  
  Sequences are fun
&lt;/h3&gt;

&lt;p&gt;A Raku &lt;a href="https://docs.raku.org/type/Seq"&gt;Seq&lt;/a&gt; is a iterable object that returns values that are generally calculated as required. There's a couple of sequences that can provide factorials. This first uses the &lt;a href="https://docs.raku.org/language/operators#index-entry-..._operators"&gt;&lt;code&gt;...&lt;/code&gt; Sequence operator&lt;/a&gt;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@F = (1,{$_ * $++}...*)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here we define our starting condition &lt;code&gt;@F[0] == 1&lt;/code&gt; then our iterator in this &lt;code&gt;$_&lt;/code&gt; is given the value of the previous item in the list and &lt;code&gt;$&lt;/code&gt; is a local state variable. This will be 1 in the first iteration so &lt;code&gt;@F[1] == 1&lt;/code&gt; and then 2, 3 and so on. We use * as the final condition meaning we will keep generating values forever, but as sequences are lazy this doesn't cause our code to die.&lt;/p&gt;

&lt;p&gt;Another way to create a Sequence would be to use [gather and take]{&lt;a href="https://docs.raku.org/syntax/gather%20take"&gt;https://docs.raku.org/syntax/gather%20take&lt;/a&gt;} to explictly define it :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my @F = lazy gather { 
    my $idx = 1; 
    my $val = 1; 
    loop {
        take $val;
        $val *= $idx++; 
    }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;A bit more wordy but sometimes this can be good. For a simple sequence like this it's probably over kill but in other cases you may fine it useful. &lt;/p&gt;

&lt;h3&gt;
  
  
  Recursion is fun too
&lt;/h3&gt;

&lt;p&gt;A classic way to do factorials (and in some languages the only way) is to use recursion. Raku lends itself to this with &lt;code&gt;multi subs&lt;/code&gt; for example :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;multi sub fact( 0 ) { 1 }

multi sub fact( UInt $N ) { $N * fact( $N - 1 ) }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here fact will recursively call itself until $N is 1 at which point the &lt;code&gt;fact(0)&lt;/code&gt; call will match and the stack can unroll. &lt;/p&gt;

&lt;p&gt;This is probably safe to do as in this challenge &lt;code&gt;$N&lt;/code&gt; can't go over 10 but it's dangerous to rely on otherwise as you may get stack overflows. Still nice to know it's easy enough.&lt;/p&gt;

&lt;h3&gt;
  
  
  Meta Ops are your friends
&lt;/h3&gt;

&lt;p&gt;When I &lt;a href="https://github.com/manwar/perlweeklychallenge-club/blob/master/challenge-072/simon-proctor/raku/ch-1.raku"&gt;did the challenge&lt;/a&gt; my first thought was to turn to Meta Operators. As &lt;code&gt;5!&lt;/code&gt; can be written as &lt;code&gt;1 * 2 * 3 * 4 * 5&lt;/code&gt; this looks to me like a reduction on the list &lt;code&gt;(1,2,3,4,5)&lt;/code&gt; with the &lt;code&gt;*&lt;/code&gt; operator. the &lt;a href="https://docs.raku.org/language/operators#index-entry-%5B%5D_(reduction_metaoperators)"&gt;&lt;code&gt;[]&lt;/code&gt; reduction metaoperator&lt;/a&gt; lets you write this like so :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sub fact(UInt $N) { [*] (1..$N) }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Note this works for &lt;code&gt;0&lt;/code&gt; as the &lt;a href="https://docs.raku.org/type/Range"&gt;Range&lt;/a&gt; &lt;code&gt;1..0&lt;/code&gt; is the list &lt;code&gt;(1)&lt;/code&gt;. &lt;/p&gt;

&lt;h2&gt;
  
  
  Finding the Trailing Zeros.
&lt;/h2&gt;

&lt;p&gt;So we've got our factorial using one of the above options how do we find trailing zeros? Well as an old school Perl dev the first thing that comes to my mind is to use a &lt;a href="https://docs.raku.org/type/Regex"&gt;Regex&lt;/a&gt;. The expression &lt;code&gt;0*$&lt;/code&gt; will match 0 or more &lt;code&gt;0&lt;/code&gt;'s at the end of a string. We then can count the length of this match and return it:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;say (fact($N) ~~ m!(0*)$!)[0].Str.codes;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We get a Match object and can get it's zeroth value which is the first capture (here's a difference in Raku Regexes, captures start at 0). We coerce this to a Str and then count the code points. And Bingo, the count of trailing 0's.&lt;/p&gt;

&lt;p&gt;And here's &lt;a href="https://dev.to/scimon/the-weekly-challenge-in-raku-week-72-part-2-12oh"&gt;Part 2&lt;/a&gt;&lt;/p&gt;

</description>
      <category>raku</category>
    </item>
    <item>
      <title>Perl Weekly Challenge in Raku Week 71 (Part 1)</title>
      <dc:creator>Simon Proctor</dc:creator>
      <pubDate>Tue, 28 Jul 2020 15:55:41 +0000</pubDate>
      <link>https://dev.to/scimon/perl-weekly-challenge-in-raku-week-71-part-1-o3h</link>
      <guid>https://dev.to/scimon/perl-weekly-challenge-in-raku-week-71-part-1-o3h</guid>
      <description>&lt;p&gt;Sorry I've been away for a while I've actually been plugging away at the Challenges for a while I've just not felt the energy to Blog about then. Partly I've been busy and partly well... 2020 you know how it is.&lt;/p&gt;

&lt;p&gt;But I figured I should get back on the horse with &lt;a href="https://perlweeklychallenge.org/blog/perl-weekly-challenge-071/"&gt;Week 71&lt;/a&gt;. &lt;/p&gt;

&lt;h2&gt;
  
  
  Challenge 1
&lt;/h2&gt;

&lt;p&gt;So Challenge 1 asked you to generate a list of length 2 to 50 unique random positive integers. Then print the lists of peaks, a peak being defined as a number in the list higher than the two numbers next to it. Sounds fun, let's dive in.&lt;/p&gt;

&lt;p&gt;Firstly we want our list size (&lt;code&gt;$N&lt;/code&gt;) that needs to be between 2 and 50. We can put this in a &lt;code&gt;MAIN&lt;/code&gt; sub with some documentation so we can run the script from the command line.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#| Generate a list of random numbers then find the peaks
sub MAIN(
    UInt $N 
    where 1 &amp;lt; * &amp;lt;= 50 #= Size of random number list
) {
    ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;As usual I'm using the &lt;code&gt;#|&lt;/code&gt; and &lt;code&gt;#=&lt;/code&gt; comments to add documentation to the function that will auto print if you run it with &lt;code&gt;-?&lt;/code&gt; or incorrect input. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;$N&lt;/code&gt; has a where clause that makes use of a &lt;a href="https://docs.raku.org/type/Whatever"&gt;Whatever Star&lt;/a&gt; to generate a code block and also operator chaining to easily test that &lt;code&gt;1 &amp;lt; $N&lt;/code&gt; and &lt;code&gt;$N &amp;lt;= 50&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;So now we want to make a list of random unique numbers between 1 and 50 up to &lt;code&gt;$N&lt;/code&gt; in length. Luckily there's an app for that!&lt;/p&gt;

&lt;p&gt;Well a method, &lt;a href="https://docs.raku.org/routine/pick"&gt;pick&lt;/a&gt; picks a random number from a list in this in this way it's similar to &lt;a href="https://docs.raku.org/routine/roll"&gt;roll&lt;/a&gt; and if you just call &lt;code&gt;list.pick&lt;/code&gt; and &lt;code&gt;list.roll&lt;/code&gt; you'll get a single random item in the list.&lt;/p&gt;

&lt;p&gt;The difference comes when you call then with an integer value. In this case you get a Sequence of items from the list and here is where the two method diverge. &lt;code&gt;list.roll(N)&lt;/code&gt; is like rolling a dice N times with all the items in the list on different sides. Each roll is distinct and the same number can come up twice.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;list.pick(N)&lt;/code&gt; is list picking N cards from a deck. You don't put them back into the deck until you've finished picking... Which makes our code to make (or pick) the random list simple enough.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my @list = (1..50).pick($N);
say "List  : {@list.join(',')}";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This makes a random list of the numbers from 1 to 50 of length &lt;code&gt;$N&lt;/code&gt; then prints it out. Ok... now to find the peaks.&lt;/p&gt;

&lt;p&gt;First thing to bear in mind, for any given point &lt;code&gt;$i&lt;/code&gt; in the list it's a peak if &lt;code&gt;@list[$i-1] &amp;lt; @list[$i] &amp;gt; @list[$i+1]&lt;/code&gt; (note we don't need to worry about equality as the numbers are unique).  &lt;/p&gt;

&lt;p&gt;Another way to look at this is if you have a list of 3 numbers (&lt;code&gt;@l&lt;/code&gt;) then the number in the middle of the list is a peak if &lt;code&gt;@l[0] &amp;lt; @l[1] &amp;gt; @l[2]&lt;/code&gt;. I can see my old friend &lt;a href="https://docs.raku.org/routine/grep"&gt;grep&lt;/a&gt; waving at me. We've come through thick and thin together and they've never let me down, sure they change their name in different places but I know if &lt;code&gt;grep&lt;/code&gt; is around my life will be easier. &lt;/p&gt;

&lt;p&gt;So I'm already seeing a plan, take the list, make it into a list of list where each is the current value and the numbers to either side. Grep for peaks then &lt;a href="https://docs.raku.org/routine/map"&gt;map&lt;/a&gt; comes in (you rarely find the two far apart) and pulls out the middle value again...&lt;/p&gt;

&lt;p&gt;So this leaves us with two questions...&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;What about the start and end values?&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;How&lt;/em&gt; do we split the list up?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Generally when you're doing functional list based manipulation you want to avoid special cases (like how to handle to two ends of the list) as it complicates matters. &lt;/p&gt;

&lt;p&gt;Of course we know that every number in the list if greater than 0 for if we put a 0 at each end of the list before dividing it into the lists of lists then we simplify things. Now our first list triplet will be &lt;code&gt;(0, @list[0], @list[1])&lt;/code&gt; and the test &lt;code&gt;(0 &amp;lt; @list[0] &amp;gt; @list[1])&lt;/code&gt; is functionally the same (in this case) as &lt;code&gt;@list[0] &amp;gt; @list[1]&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;So our list of peaks starts simply enough :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@peaks = ( 0, |@list, 0 ); 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This uses the &lt;code&gt;|&lt;/code&gt; operator to "slip" our list into the outer list creator (the brackets). If we don't do that you end up with 3 items in @peaks, one of which is a list... &lt;/p&gt;

&lt;p&gt;Great so now we just have to divide this list into overlapping sets of three items. &lt;/p&gt;

&lt;p&gt;It's at this point the inexperienced Raku developer will start writing a bunch of nested for loops and all this kind of stuff. &lt;/p&gt;

&lt;p&gt;This isn't wrong but I often find that if I have a simple problem in Raku the first thing to do is &lt;a href="https://docs.raku.org"&gt;Read the Docs&lt;/a&gt;. In this case we specifically want to look at the &lt;a href="https://docs.raku.org/routine/rotor"&gt;rotor&lt;/a&gt; method. &lt;/p&gt;

&lt;p&gt;Rotor is a new friend of grep and map, Raku has brought a &lt;em&gt;lot&lt;/em&gt; of friends to the "Lets play about with lists" party. Which is cool, especially when you realise just how many things count as "lists" for this.&lt;/p&gt;

&lt;p&gt;But I digress. What rotor does is divide a list into sublists of a given length so :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(1,2,3,4).rotor(2) == ((1,2),(3,4))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Ok so this is starting to look right of only there was some where to say :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(1,2,3,4).rotor(THING) == ((1,2),(2,3),(3,4)) 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And do it for 3 items... well guess what, you totally can. Rotor has a &lt;em&gt;lot&lt;/em&gt; of options on how you call it and I'm going to focus on one for this job. &lt;/p&gt;

&lt;p&gt;If you call rotor and pass a &lt;a href="https://docs.raku.org/type/Pair"&gt;Pair&lt;/a&gt; then it treat's this as &lt;code&gt;length =&amp;gt; offset&lt;/code&gt; and it will skip offset many items before making the next sub list. &lt;/p&gt;

&lt;p&gt;Which is nice when you find that &lt;code&gt;offset&lt;/code&gt; can be a negative, in which case you get overlapping sublists. &lt;/p&gt;

&lt;p&gt;Our &lt;code&gt;@peaks&lt;/code&gt; now becomes :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my @peaks = ( 0, |@list, |0 )
    .rotor(3 =&amp;gt; -2)
    .grep( { $_[0] &amp;lt; $_[1] &amp;gt; $_[2] } )
    .map( { $_[1] } );
say "Peaks : {@peaks.join(',')}";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Get the list, split into sublists, grep for peaks, pull out the middle number. All nice and simple, no special cases and functional. If we wanted (and the list was longer) we could run these steps in parallel. &lt;/p&gt;

&lt;p&gt;Nice and easy. Of course I've written a lot of stuff about what ended up being a 4 line bit of code. As the second solution is a bit longer I'll do a second post about it later. &lt;/p&gt;

&lt;p&gt;Fingers crossed and 2020 willing. &lt;/p&gt;

</description>
      <category>raku</category>
    </item>
    <item>
      <title>Perl Weekly Challenge in Raku : Week 55</title>
      <dc:creator>Simon Proctor</dc:creator>
      <pubDate>Tue, 07 Apr 2020 08:43:51 +0000</pubDate>
      <link>https://dev.to/scimon/perl-weekly-challenge-in-raku-week-55-4lk1</link>
      <guid>https://dev.to/scimon/perl-weekly-challenge-in-raku-week-55-4lk1</guid>
      <description>&lt;p&gt;So it's been a few weeks, I don't know about you but I've been a bit stressed so blogging about the challenges has been a bit hard. Still I'm also lucky to be &lt;a href="https://careers.zoopla.co.uk/"&gt;working in a job I enjoy&lt;/a&gt; from home. Stay safe everyone and lets take a look at &lt;a href="https://perlweeklychallenge.org/blog/perl-weekly-challenge-055/"&gt;this weeks challenges&lt;/a&gt; &lt;/p&gt;

&lt;h2&gt;
  
  
  Challenge 1
&lt;/h2&gt;

&lt;p&gt;As is often the way my first thought on a challenge like this is to approach it with brute force and ignorance. I generally find that throwing computing power at the problem can often solve it quickly, if it doesn't I'll use my more valuable (and somewhat ageing) brainpower instead.&lt;/p&gt;

&lt;p&gt;The first thing I decided was I'd represent my binary strings as Arrays, this is because I find bit twiddling annoying at the best of times and reserve it for instances when it's absolutely necessary. I value readability of my code and I just can't read masks and binary wibbly things all the easily. &lt;/p&gt;

&lt;p&gt;So with that in mind here's a simple function that given an array of &lt;code&gt;1&lt;/code&gt;s and &lt;code&gt;0&lt;/code&gt;s plus a start and end index flips all the ones in between.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sub flip( @bin is copy, $l, $r ) {
    @bin[$l..$r] = @bin[$l..$r].map( { abs($_-1) } );
    @bin;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This makes use of a few neat things. Firstly you can assign to an array slice so we modify the slice and assign back into it. The second thing is that &lt;code&gt;abs(x-1)&lt;/code&gt; for &lt;code&gt;x=0&lt;/code&gt; and &lt;code&gt;x=1&lt;/code&gt; returns the flipped value as &lt;code&gt;abs(0-1) == abs(-1) == 1&lt;/code&gt; and &lt;code&gt;abs(1-1) == 0&lt;/code&gt;. So it makes the flipping itself nice and easy. &lt;/p&gt;

&lt;p&gt;After that we just need to loop through all the possible values for &lt;code&gt;l&lt;/code&gt; and &lt;code&gt;r&lt;/code&gt; and keep track of the results with the most elements. For this we can use a stream cache, where we store the value of the most elements found and the list of all those results. For each new result if it's got more &lt;code&gt;1&lt;/code&gt;s than the current highest we reset the list of just have out new result and update the highest value. If it's got the same number of &lt;code&gt;1&lt;/code&gt;s we add it to the current list, otherwise we ignore it.&lt;/p&gt;

&lt;p&gt;This is a useful trick when you're dealing with a stream of data and you know what you're looking but you don't know how much data you're going to have. Putting everything into a hash and iterating over that after can lead to memory issues. &lt;/p&gt;

&lt;p&gt;Anyhow, here's the main loop.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#| Given a binary string find the start and end points
#| for flipping the bits that results in the most 1's
#| in the final string
sub MAIN( Str $bin where { m!^ &amp;lt;[10]&amp;gt;+ $! } ) {
    my @bin = $bin.comb;

    my @results;
    my $len = 0;

    for 0..@bin.elems-1 -&amp;gt; $l {
        for $l..@bin.elems-1 -&amp;gt; $r {
            my @res = flip(@bin,$l,$r);
            given @res.grep(* == 1).elems {
                when * &amp;gt; $len {
                    $len = $_;
                    @results = [ { l =&amp;gt; $l, r =&amp;gt; $r, bin =&amp;gt; @res.join("") }, ];
                }
                when $len {
                    @results.push( { l =&amp;gt; $l, r =&amp;gt; $r, bin =&amp;gt; @res.join("") } );
                }
            }
        }
    }
    say "Max 1's : {$len}";
    say "{$_&amp;lt;l&amp;gt;} -&amp;gt; {$_&amp;lt;r&amp;gt;} : {$_&amp;lt;bin&amp;gt;}" for @results;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Challenge 2
&lt;/h2&gt;

&lt;p&gt;So Challenge 2 is about doing a Wave Sort, which is where a list &lt;code&gt;a,b,c,d,e&lt;/code&gt; is sorted so that &lt;code&gt;a &amp;gt;= b &amp;lt;= c &amp;gt;= d &amp;lt;= e&lt;/code&gt; and so on. There's probably a nifty way to make a custom infix operator that can handle this using chaining but I decided to go old school (Edinburgh University AI department in the 90's to be exact) and use the Prolog like abilities of the Raku Multi Dispatch model.&lt;/p&gt;

&lt;p&gt;First up we need a way to get the unique permutations of a list. The challenge states your list can have non unique values in and the standard &lt;a href="https://docs.raku.org/routine/permutations"&gt;permutations&lt;/a&gt; method treats each element as unique so for the the &lt;code&gt;(1,1)&lt;/code&gt; will give two results &lt;code&gt;(1,1),(1,1)&lt;/code&gt; which is not what we want.&lt;/p&gt;

&lt;p&gt;My original version of this got all the permutations joined them with commas and put the in a set to get the unique keys and split them up. The problem with this is &lt;code&gt;permutations&lt;/code&gt; returns a Sequnece which is evaluated lazily whilst that had to calculate all the permutations before anything could be done.&lt;/p&gt;

&lt;p&gt;So then I came up with a nest method involving &lt;a href="https://docs.raku.org/syntax/gather%20take"&gt;gather / take&lt;/a&gt; and a hash to give a sequence of values.&lt;/p&gt;

&lt;p&gt;And then while writing this I thought, surely Raku has a &lt;a href="https://docs.raku.org/routine/unique"&gt;unique&lt;/a&gt; method? And lo and behold my final unique permissions sub:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sub unique-perms ( @input ) {
    @input.permutations.unique(:as(*.join(",")));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This uses the &lt;code&gt;:as&lt;/code&gt; option to specific how to change the input for &lt;code&gt;===&lt;/code&gt; comparison and it slightly fasted then using &lt;code&gt;:with(&amp;amp;infix:&amp;lt;~~&amp;gt;)&lt;/code&gt;. This gives us a sequence which means our code to check each permutation and see if it's valid is simple enough and can make use of &lt;a href="https://docs.raku.org/routine/race"&gt;race&lt;/a&gt; to give us simple threading.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#| Given a list of integers return all the wave sorted lists
multi sub MAIN( *@input where { $_.elems &amp;gt;= 2 &amp;amp;&amp;amp; $_.all ~~ Int } ) {
    .say for unique-perms( @input ).race.grep( -&amp;gt; @l { is-wave( 'gte', |@l ) } );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;...&lt;/p&gt;

&lt;p&gt;Oh yeah. What's in &lt;code&gt;is-wave&lt;/code&gt; and where's the Prolog you talked about? &lt;/p&gt;

&lt;p&gt;So first thing you'll note is &lt;code&gt;is-wave&lt;/code&gt; take a staring string argument of &lt;code&gt;gte&lt;/code&gt; (for &lt;code&gt;&amp;gt;=&lt;/code&gt;) and then take the array the permutation as a set of arguments by having the &lt;code&gt;|&lt;/code&gt; slip operator in front (I believe some language use &lt;code&gt;...&lt;/code&gt; to do this?) &lt;/p&gt;

&lt;p&gt;So lets go through some possible ways this function could be called :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;multi sub is-wave( 'gte', Int $a, Int $b where { $b &amp;gt; $a }, *@ ) {
    False 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;So if we call it with &lt;code&gt;gte&lt;/code&gt;, two integers (&lt;code&gt;$a&lt;/code&gt; and &lt;code&gt;$b&lt;/code&gt;) and some more positional arguments &lt;code&gt;*@&lt;/code&gt; but &lt;code&gt;$b&lt;/code&gt; is greater then &lt;code&gt;$a&lt;/code&gt; we return &lt;code&gt;False&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;There are two other simple results :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;multi sub is-wave( 'gte', Int $a, Int $b where { $a &amp;gt;= $b } ) { 
    True 
}
multi sub is-wave( 'gte', Int $a, Int $b where { $a &amp;lt; $b } ) { 
    False 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;There's two cases where we call &lt;code&gt;is-wave&lt;/code&gt; with &lt;code&gt;gte&lt;/code&gt; and just two arguments. In on case &lt;code&gt;$a&lt;/code&gt; &lt;em&gt;is&lt;/em&gt; &lt;code&gt;&amp;gt;=&lt;/code&gt; &lt;code&gt;$b&lt;/code&gt; so we return &lt;code&gt;True&lt;/code&gt; and in the other it isn't so we return &lt;code&gt;False&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This leaves us with one last possibly situation. More than two arguments and &lt;code&gt;$a &amp;gt;= $b&lt;/code&gt;...&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;multi sub is-wave( 
                   'gte', 
                   Int $a, 
                   Int $b where { $a &amp;gt;= $b }, 
                   $c, 
                   *@r 
                 ) { 
    True &amp;amp;&amp;amp; is-wave( 'lte', $b, $c, |@r ); 
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;So here we take &lt;em&gt;3&lt;/em&gt; values where &lt;code&gt;$a &amp;gt;= $b&lt;/code&gt; then we recurse into &lt;code&gt;is-wave&lt;/code&gt; but now we pass &lt;code&gt;lte&lt;/code&gt;, &lt;code&gt;$b&lt;/code&gt;, &lt;code&gt;$c&lt;/code&gt; and the rest of the list &lt;code&gt;@r&lt;/code&gt; (this may be empty).&lt;/p&gt;

&lt;p&gt;The code for the &lt;code&gt;lte&lt;/code&gt; options are basically the same giving use this :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;multi sub is-wave( 'lte', Int $a, Int $b where { $a &amp;lt;= $b } )
    { True }
multi sub is-wave( 'lte', Int $a, Int $b where { $a &amp;gt; $b } )
    { False }
multi sub is-wave( 'gte', Int $a, Int $b where { $a &amp;gt;= $b } )          
    { True }
multi sub is-wave( 'gte', Int $a, Int $b where { $a &amp;lt; $b } )           
    { False }
multi sub is-wave( 'gte', Int $a, Int $b where { $a &amp;lt; $b }, *@ )       
    { False }
multi sub is-wave( 'lte', Int $a, Int $b where { $a &amp;gt; $b }, *@ )       
    { False }
multi sub is-wave( 'gte', Int $a, Int $b where { $a &amp;gt;= $b }, $c, *@r )
    { True &amp;amp;&amp;amp; is-wave( 'lte', $b, $c, |@r ); }
multi sub is-wave( 'lte', Int $a, Int $b where { $a &amp;lt;= $b }, $c, *@r )        
    { True &amp;amp;&amp;amp; is-wave( 'gte', $b, $c, |@r ); }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;There's probably a more elegant way to solve the problem without my brute force "Find every possible list and filter out the right ones" way but I do love that piece of code right there for it's simple elegance and the power that multi dispatch can bring to the table. &lt;/p&gt;

</description>
      <category>raku</category>
    </item>
    <item>
      <title>Perl Weekly Challenge In Raku : Week 50</title>
      <dc:creator>Simon Proctor</dc:creator>
      <pubDate>Wed, 04 Mar 2020 09:52:24 +0000</pubDate>
      <link>https://dev.to/scimon/perl-weekly-challenge-in-raku-week-50-2411</link>
      <guid>https://dev.to/scimon/perl-weekly-challenge-in-raku-week-50-2411</guid>
      <description>&lt;h2&gt;
  
  
  Challenge 1
&lt;/h2&gt;

&lt;p&gt;For some reason people have been giving me money for a number of years now to solve problems with computers. Which is nice. Often these problems involve ranges and whether they intersect (it's &lt;em&gt;very&lt;/em&gt; often date ranges). &lt;/p&gt;

&lt;p&gt;As such I've drawn a diagram like this very often on a bit of paper to dredge up the memory of how to do it :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   |---------| b
 1 2 3 4 5 6 7 8 9   == [ [1,3] , [2,7], [6,8] ]
 |---| a   |---| c
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we have 3 sets of pairs. There's a simple rule to determine if they intersect. Given 2 pairs (call them x and y they intersect if):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x[0] &amp;lt;= y[1] &amp;amp;&amp;amp; y[0] &amp;lt;= x[1]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And that's it, it's really that simple. Lets look at our example :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a and b ? a[0] &amp;lt;= b[1] &amp;amp;&amp;amp; b[0] &amp;lt;= a[1] == 1 &amp;lt;= 7 &amp;amp;&amp;amp; 2 &amp;lt;= 3 == True
b and c ? b[0] &amp;lt;= c[1] &amp;amp;&amp;amp; c[0] &amp;lt;= b[1] == 2 &amp;lt;= 6 &amp;amp;&amp;amp; 7 &amp;lt;= 8 == True
a and c ? a[0] &amp;lt;= c[1] &amp;amp;&amp;amp; c[0] &amp;lt;= a[1] == 1 &amp;lt;= 8 &amp;amp;&amp;amp; 6 &amp;lt;= 3 == False 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this knowledge the code to group unions is simple. Sort our list of lists, take the first item if it intersects with the second then expand it to cover the range of the two. Otherwise put it in the output and continue comparing the next one to the list... It's probably easer to read the code :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;subset IntPair of Str where m!^ \d+ "," \d+ $!;

#| Given a list of Integer Pairs print the sorted list of pairs with intersections combined
multi sub MAIN (
    *@pairs where { $_.all ~~ IntPair } #= List of comma seperated integer pairs
) {
    my @working = @pairs.map(*.split(",")).sort( *[0] &amp;lt;=&amp;gt; *[0] );
    my @out;
    my $current = @working.shift;

    while ( @working ) {
        my $next = @working.shift;
        if ( $current[0] &amp;lt;= $next[1] &amp;amp;&amp;amp; $current[1] &amp;gt;= $next[0] ) {
            $current = [ $current[0] &amp;lt; $next[0] ?? $current[0] !! $next[0],
                         $current[1] &amp;gt; $next[1] ?? $current[1] !! $next[1]  ]; 
        } else {
            @out.push( $current );
            $current = $next;
        }
    }
    @out.push( $current ).map( *.join(",") ).join(" ").say;
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As normal I have wrapped this in a nice MAIN function to get some documentation and input checking.&lt;/p&gt;

&lt;h3&gt;
  
  
  A thought on my process
&lt;/h3&gt;

&lt;p&gt;Personally when I do the challenge I try and complete it using just the language alone. Admittedly this is quite simple with Raku. In my &lt;a href="https://careers.zoopla.co.uk/"&gt;day job&lt;/a&gt; I mostly work in Perl and will always reach for CPAN to see if someone has solved a problem before tackling it myself. &lt;/p&gt;

&lt;p&gt;But I do the challenges because I want to explore the problem space and have a think about it. The thing is there is a Raku module (admittedly it's in a Beta state) that would help here &lt;a href="https://modules.raku.org/dist/Range::SetOps:cpan:SCIMON"&gt;Range::SetOps&lt;/a&gt; written by... oh me. &lt;/p&gt;

&lt;p&gt;Ranges in Raku have a weird dual state, the represent a range between two points but if you look at them in the wrong way they will transform into a list of discrete entities. &lt;/p&gt;

&lt;p&gt;For instance &lt;code&gt;5.5 ~~ 1..10&lt;/code&gt; will return &lt;code&gt;True&lt;/code&gt; because &lt;code&gt;5.5&lt;/code&gt; is in the range &lt;code&gt;1..10&lt;/code&gt; but &lt;code&gt;5.5 (elem) 1..10&lt;/code&gt; will return &lt;code&gt;False&lt;/code&gt; because the Range is coerced into a Set but making it a list of discrete items. &lt;/p&gt;

&lt;p&gt;What Range::SetOps does is (again still in Beta, there's some flaws I really should finish it) overload the &lt;a href="https://docs.raku.org/language/setbagmix"&gt;Set Operators&lt;/a&gt; when they handle &lt;code&gt;Ranges&lt;/code&gt; or &lt;code&gt;Sets&lt;/code&gt; that contain &lt;code&gt;Ranges&lt;/code&gt; to return either &lt;code&gt;Ranges&lt;/code&gt; or &lt;code&gt;Sets&lt;/code&gt; of &lt;code&gt;Ranges&lt;/code&gt; based on the operation.&lt;/p&gt;

&lt;p&gt;For example without Range::SetOps loaded :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(2..7) ∪ (3..9) == set(2,3,4,5,6,7,8,9)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With Range::SetOps loaded :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(2..7) ∪ (3..9) == set(2..9)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With Range::SetOps our job is easier. Make our input lists into ranges. Find the Union Set of them then make them back into lists :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;use Range::SetOps;
subset IntPair of Str where m!^ \d+ "," \d+ $!;

#| Given a list of Integer Pairs print the sorted list of pairs with intersections combined
multi sub MAIN (
    *@pairs where { $_.all ~~ IntPair } #= List of comma seperated integer pairs
) {
    ([∪] @pairs.map( { ($_[0]..$_[1]) } )).keys.map( { [$_.min,$_.max] } ).sort.map( *.join(",") ).join(" ").say;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we use the reduction meta operator &lt;code&gt;[]&lt;/code&gt; to chain the &lt;code&gt;∪&lt;/code&gt; intersection operations and end up with a &lt;code&gt;Set&lt;/code&gt; of &lt;code&gt;Ranges&lt;/code&gt; which we then turn back into a list of lists, prettify and print. &lt;/p&gt;

&lt;p&gt;And yes I really should get round to finishing it, mostly it's handling Ranges with exceptions &lt;code&gt;(^1..^10)&lt;/code&gt; for example. &lt;/p&gt;

&lt;h2&gt;
  
  
  Challenge 2
&lt;/h2&gt;

&lt;p&gt;There's one thing about the description for this challenge I wasn't sure of which is whether you can have duplicate numbers. I checked and you can't. In which case my first intuitive thought for how to check if a number is Noble is simple enough. &lt;/p&gt;

&lt;p&gt;Sort the list. Take the first number if it equals the length of the remaining list it's Noble. Repeat while you have a list.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#| Generate and display a random list of n integers (default 10) between 1 and max (default 30)
#| Then print the Noble Integers in the list
multi sub MAIN (
    UInt :n(:$number) = 10, #= Number of values to generate
    UInt :m(:$max) where { $max &amp;gt; $number } = 50  #= Maximum value (must be greater then $n)
) {
    my @list = (1..$max).pick($number);
    say "Generated List : {@list.join(",")}";
    MAIN( @list );
}

#| Given a list of Integers print the noble integers in the list
multi sub MAIN (
    *@values is copy where { $_.all ~~ UInt } #= Space seperated list of Intgers to check
) {
    @values.=sort;
    while ( @values ) {
        my $val = @values.shift;
        say $val if $val == @values.elems;
    }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Last night though my brain decided to have a think about the problem a bit more. The challenge asks can there be multiple noble numbers in a list? &lt;/p&gt;

&lt;p&gt;So lets look at our options. &lt;/p&gt;

&lt;h3&gt;
  
  
  Can we have a list with 0 Noble numbers?
&lt;/h3&gt;

&lt;p&gt;This is trivial to prove by example &lt;code&gt;[3,4,5]&lt;/code&gt; is a simple example. But we also can glean a rule. &lt;/p&gt;

&lt;p&gt;Given a sorted list of length &lt;code&gt;L&lt;/code&gt; if the first number is greater than &lt;code&gt;L-1&lt;/code&gt; then the list has no Noble numbers. &lt;/p&gt;

&lt;h3&gt;
  
  
  Can we have a list with 1 Noble number?
&lt;/h3&gt;

&lt;p&gt;Here we can work from the rule given before. If we have a sorted list of length &lt;code&gt;L&lt;/code&gt; and it's first value is &lt;code&gt;L-1&lt;/code&gt; then it's a noble number. &lt;/p&gt;

&lt;p&gt;As you can remove all the numbers &lt;em&gt;before&lt;/em&gt; the first Noble number then many lists can have a noble number in.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[1,2,3,4,5,6,7,8,11,15] = 5 is Noble
[5,6,7,8,11,15] = 5 is Noble

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Any amount of numbers (between &lt;code&gt;1&lt;/code&gt; and &lt;code&gt;4&lt;/code&gt;) can go before the &lt;code&gt;5&lt;/code&gt; and it will still be Noble. &lt;/p&gt;

&lt;p&gt;There's a whole bunch of other stuff about for a given length of list what the range of possible Noble numbers are but I'm not interested in that right now.&lt;/p&gt;

&lt;h3&gt;
  
  
  Can we have a list with 2 Noble Numbers?
&lt;/h3&gt;

&lt;p&gt;Assume we have a list with a Noble number in &lt;code&gt;N&lt;/code&gt; this means there are &lt;code&gt;N&lt;/code&gt; numbers following it in the list and &lt;code&gt;0&lt;/code&gt; to &lt;code&gt;N-1&lt;/code&gt; numbers before it in the list. &lt;/p&gt;

&lt;p&gt;Could &lt;code&gt;N-1&lt;/code&gt; be Noble? &lt;em&gt;No&lt;/em&gt;. &lt;/p&gt;

&lt;p&gt;There are &lt;code&gt;N+1&lt;/code&gt; (&lt;code&gt;N&lt;/code&gt; and the &lt;code&gt;N&lt;/code&gt; numbers following) after it. The same hold true for any number less than &lt;code&gt;N&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Could &lt;code&gt;N+1&lt;/code&gt; be Noble? &lt;em&gt;No&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;There are &lt;code&gt;N-1&lt;/code&gt; number following it (as it has to come after &lt;code&gt;N&lt;/code&gt; in the list and we know that there are &lt;code&gt;N&lt;/code&gt; numbers in the following list). Again this holds true for all values greater than &lt;code&gt;N&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;So No. A given list will have either &lt;code&gt;0&lt;/code&gt; or &lt;code&gt;1&lt;/code&gt; Noble number. &lt;/p&gt;

&lt;p&gt;Neat.&lt;/p&gt;

</description>
      <category>raku</category>
    </item>
    <item>
      <title>Perl Weekly Challenge - Week 49</title>
      <dc:creator>Simon Proctor</dc:creator>
      <pubDate>Tue, 25 Feb 2020 12:03:44 +0000</pubDate>
      <link>https://dev.to/scimon/perl-weekly-challenge-week-49-33a7</link>
      <guid>https://dev.to/scimon/perl-weekly-challenge-week-49-33a7</guid>
      <description>&lt;p&gt;So this weeks challenges are a bit of maths and a bit of computer science which is nice.&lt;/p&gt;

&lt;h2&gt;
  
  
  Challenge 1
&lt;/h2&gt;

&lt;p&gt;Find the first multiple of a given number that is written using just &lt;code&gt;1&lt;/code&gt;'s and &lt;code&gt;0&lt;/code&gt;'s. This is one of these times where Raku's infinite lazy sequences just &lt;em&gt;fit&lt;/em&gt; with the request.&lt;/p&gt;

&lt;p&gt;First we make a sequence of the multiples of x :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;($x,*+$x...*)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Then we get the first item in the list that fulfils our requirements :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;($x,*+$x...*).first( { $_ ~~ m!^ &amp;lt;[10]&amp;gt;+ $! } )
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;(I started using &lt;code&gt;!&lt;/code&gt; as a regex delimiter years ago in Perl and carried on in Raku. It's really helpful when you're dealing with file paths and URL's as you don't need to escape the values.) &lt;/p&gt;

&lt;p&gt;Finally we can wrap this in a &lt;code&gt;MAIN&lt;/code&gt; sub, it's not needed but it's nice and can add some documentation which is always nice.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#| Find the first multiple of x made of only 1's and 0's
sub MAIN(
    UInt $x #= Number to look for multiple of
) {
    ( $x, * + $x...* ).hyper.first( { $_ ~~ m!^ &amp;lt;[10]&amp;gt;+ $! } ).say;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And there we go. Though... I would not advise running it for a multiple of 9. This is because if you add up all the digits in a multiple of 9 and keep doing so until you have 1 digit left you &lt;em&gt;always&lt;/em&gt; get 9. &lt;/p&gt;

&lt;p&gt;This would imply that the first multiple of 9 that has only &lt;code&gt;1&lt;/code&gt;'s and &lt;code&gt;0&lt;/code&gt;'s in it is &lt;code&gt;111111111&lt;/code&gt; (which is &lt;code&gt;9 * 12345679&lt;/code&gt;). Working that out does take this code a while. another option is to use a lazy gather / take block  like so :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;my @seq = lazy gather {
    my $current = $x;
    loop {
        take $current;
        $current += $x;
    }
};

@seq.first( { $_ ~~ m!^ &amp;lt;[10]&amp;gt;+ $! } ).say;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This uses less memory but I still get bored waiting for it for calculate the first value for &lt;code&gt;9&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;...&lt;/p&gt;

&lt;p&gt;So writing this I had a brain spasm and realised I was approaching the problem in the wrong direction. Why not calculate the numbers made of &lt;code&gt;1&lt;/code&gt;'s and &lt;code&gt;0&lt;/code&gt;'s which can be easily done using binary and Raku's duck typing. This gives us the new code :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#| Find the first multiple of x made of only 1's and 0's
sub MAIN(
    UInt $x #= Number to look for multiple of
) {
    my @seq = lazy gather {
        my $current = 1;
        loop {
            take $current.base(2);
            $current++;
        }
    }

    @seq.first( * %% $x ).say;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This makes use of the fact that &lt;code&gt;Int.base&lt;/code&gt; returns a &lt;code&gt;Str&lt;/code&gt; but if you try and divide it then Raku auto casts it back to an &lt;code&gt;Int&lt;/code&gt; in base 10. Job done and now you can get the value for &lt;code&gt;9&lt;/code&gt; or &lt;code&gt;81&lt;/code&gt; is super fast time. Awesome! &lt;/p&gt;

&lt;h2&gt;
  
  
  Challenge 2
&lt;/h2&gt;

&lt;p&gt;So challenge 2 comes in two parts. Make an LRU Cache and demonstrate it's use. The "proper" Computer Science thing to do here would involve linked lists. But I generally find that trying to jam linked lists into high level languages (which under the hood use them) is generally more trouble than it's worth. &lt;/p&gt;

&lt;p&gt;So I'm going with a simple idea, a hash and a list of keys. Each time I do something with the hash (getting or setting a value) I put key onto the list at the front :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[1,2,3] =&amp;gt; [3,1,2,3]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;reset it to the unique values : &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[3,1,2]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;then if it's too long pop the last value off the list. &lt;/p&gt;

&lt;p&gt;Here's the class I made for that :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Cache::LRU {

    has Int $!capacity where * &amp;gt; 0;
    has %!cache = {};
    has @!key-list = [];

    submethod BUILD ( :$capacity ) { $!capacity = $capacity }

    method !freshen ( $key ) {
        @!key-list.unshift($key).=unique;
        if @!key-list.elems &amp;gt; $!capacity {
            %!cache{@!key-list.pop}:delete;
        }
    }

    method current () {
        return @!key-list;
    }

    method get( $key ) {
        if %!cache{$key}:exists {
            self!freshen( $key );
            return %!cache{$key};
        }
        return Any;
    }

    method set( $key, $value ) {
        %!cache{$key} = $value;
        self!freshen( $key );
        return $value;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Note that this code isn't thread safe. If you wanted to use it in the wild you probably want to pull in &lt;a href="https://modules.raku.org/dist/OO::Monitors:cpan:JNTHN"&gt;OO::Monitors&lt;/a&gt; to wrap the &lt;code&gt;freshen&lt;/code&gt;, &lt;code&gt;set&lt;/code&gt; and &lt;code&gt;get&lt;/code&gt; methods. Also &lt;code&gt;current&lt;/code&gt; only exists to demonstrate the cache.&lt;/p&gt;

&lt;p&gt;Now to demonstrate it I decided to make a nice terminal interface like so :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#| Interactive LRU Cache example. Call with cache capacity
sub MAIN (
    Int $capacity where * &amp;gt; 0 #= Cache capacity (must be greater than zero)
) {
    my $cache = Cache::LRU.new( :$capacity );

    my $done = False;

    my multi sub action( "get", $key ) {
        say $cache.get($key) // "Not found";
    };
    my multi sub action( "set", $key, $value ) {
        $cache.set( $key, $value );
        say "Set $key to $value";
    };
    my multi sub action( "keys" ) {
        say "Current Keys : {$cache.current().join(",")}";
    };
    my multi sub action( "quit" ) {
        say "Bye";
        $done = True;
    };
    my multi sub action( *@ ) {
        say "I'm sorry Dave I don't know how to do that.";
        say "Valid options are :\n\tget \{key\}\n\tset \{key\} \{value\}\n\tkeys\n\tquit";
    };

    say "Welcome to the cache demo\nValid options are :\n\tget \{key\}\n\tset \{key\} \{value\}\n\tkeys\n\tquit";

    while ! $done {
        my @input = ( prompt "What would you like to do? " ).words;
        action( |@input );        
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;So I setup a set of local multi dispatch sub's that have access to the Cache object and the loop flag then just loop round prompting for input. &lt;/p&gt;

</description>
      <category>perl</category>
      <category>challenges</category>
      <category>raku</category>
    </item>
    <item>
      <title>Perl Weekly Challenge : Week 48</title>
      <dc:creator>Simon Proctor</dc:creator>
      <pubDate>Mon, 17 Feb 2020 12:10:34 +0000</pubDate>
      <link>https://dev.to/scimon/perl-weekly-challenge-week-42-2oo2</link>
      <guid>https://dev.to/scimon/perl-weekly-challenge-week-42-2oo2</guid>
      <description>&lt;p&gt;I've decided I'm going to try blogging about my attempts at the &lt;a href="https://perlweeklychallenge.org/"&gt;Perl Weekly Challenge&lt;/a&gt; which I've been doing since it started. Generally I do my challenge in &lt;a href="https://raku.org/"&gt;Raku&lt;/a&gt; the language formally known as Perl6.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://perlweeklychallenge.org/blog/perl-weekly-challenge-048/"&gt;This weeks challenge&lt;/a&gt; has a couple of fun parts. If you've not tried it yet you might want to come back after you have.&lt;/p&gt;

&lt;h2&gt;
  
  
  Challenge 1
&lt;/h2&gt;

&lt;p&gt;So I'd seen a video on this before it's called &lt;a href="https://www.youtube.com/watch?v=uCsD3ZGzMgE"&gt;the Josephus Problem&lt;/a&gt; so I knew there was a mathematical solution to it.... but I couldn't remember it.&lt;/p&gt;

&lt;p&gt;As is often the way I went a bit above and beyond and worked out a function to give the survivor number for any number of swordsmen. My thinking about it was simple. Get a list of number from 1 to 50, take the first two from the front. The first survives the second is dead. Put the survivor at the end of the list. Repeat until you have 1 survivor :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#| Calculate the survivor of the swordsmen suicide pact
multi sub MAIN(
    UInt $swords = 50, #= Number of swordsmen (default 50)
) {
    my @men = [1..$swords];
    while ( @men.elems &amp;gt; 1 ) {
        my ( $alive, $dead ) = @men.splice(0,2);
        @men.push($alive);
    }

    say "Survivor of $swords is number {@men[0]}";
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;With that I was able to run the test for lots of different value and worked out the mathematical solution. Given a number of swordsmen (s) we find p where p &amp;lt; s and p is a power of 2. Then the number of the survivor is the nth odd number where n = s - p. &lt;/p&gt;

&lt;p&gt;For example for s = 50, p = 32 and n is the 18th odd number (indexed on 0) which is 37.&lt;/p&gt;

&lt;p&gt;The code for this :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#| Calculate mathematically
multi sub MAIN(
    "math", 
    UInt $swords = 50, #= Number of swordsmen
) {
    my $low-power = (1,* * 2...*).first(* &amp;gt; $swords) div 2;
    say "Survivor of $swords is number {(1,3,5...*)[$swords - $low-power]}";
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Couple of fun uses of Raku &lt;a href="https://docs.raku.org/language/operators#index-entry-sequence_operator"&gt;sequences&lt;/a&gt; one to generate the powers of 2 and the second to generate the list of odd numbers.&lt;/p&gt;

&lt;h2&gt;
  
  
  Challenge 2
&lt;/h2&gt;

&lt;p&gt;For challenge 2 I initially worked on the theory I'll look at every date between 2020-01-01 and 2999-12-31 and look for palindromes. Turns out... that's a lot of days (357937 to be exact) and it take a while. Even when you use &lt;code&gt;.hyper&lt;/code&gt; to thread the tests over multiple cores. But then I had a thought.&lt;/p&gt;

&lt;p&gt;If I went through every month and day combination that's 12 x 31 (we'll worry about out of range values in a second) and that's only 372 to check. If we take the month and day and flip it to get a year if we can check it's valid and it's between our start and end dates. &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#| Find the palendromic numbers (writen mmddyyy) between 2000-01-01 and 2999-01-01
sub MAIN() {
    my sub df( Date $d) {
        # Bleh American dates
        sprintf "%02d%02d%04d", .month, .day, .year given $d;
    }

    constant START = Date.new(2000,1,1,formatter =&amp;gt; &amp;amp;df);
    constant END = Date.new(2999,12,31, formatter =&amp;gt; &amp;amp;df);

    my @out;

    for (1..12) -&amp;gt; $month {
        for (1..31) -&amp;gt; $day {
            my $date;
            my $year = sprintf( "%02d%02d", $month, $day ).flip;
            try {
                $date = Date.new($year,$month,$day,formatter =&amp;gt; &amp;amp;df);
            }
            next unless $date;
            next unless START &amp;lt;= $date &amp;lt;= END;
            @out.push($date);
        }
    }

    .say for @out.sort;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;I hope that all makes sense. Feel free to drop a comment if you've got questions or thoughts. &lt;/p&gt;

</description>
      <category>raku</category>
      <category>challenge</category>
    </item>
    <item>
      <title>My First Perl Conference</title>
      <dc:creator>Simon Proctor</dc:creator>
      <pubDate>Mon, 20 Aug 2018 14:57:24 +0000</pubDate>
      <link>https://dev.to/scimon/my-first-perl-conference-2j6d</link>
      <guid>https://dev.to/scimon/my-first-perl-conference-2j6d</guid>
      <description>&lt;h4&gt;
  
  
  By Simon aged 40... something
&lt;/h4&gt;

&lt;p&gt;I've been writing Perl code since I picked up a copy of Learning Perl in my local bookshop in 2001 or so. At the time I was working there, running the computer books department. My time at university had turned me off the idea of programming as a career, I found the theory of computer science to dry for me. &lt;/p&gt;

&lt;p&gt;So reading about Perl, a language that felt like language rather than maths really appealed to me. A few months later I got a Junior Developer role and began my career as a developer. &lt;/p&gt;

&lt;p&gt;Now we fast forward to 2018, I've been a Perl dev for 17 years working my way up to Senior and have yet to manage to get to a Perl Conference (European or American). As the 2018 one was planned for Glasgow and I have family in Scotland it was a no-brainer. I took a week off and put myself down as a speaker. Why? Because in the last few years I have got very interested in and impressed by &lt;a href="https://perl6.org/"&gt;Perl6&lt;/a&gt;. I have given a couple of talks at the &lt;a href="http://london.pm.org/"&gt;London Perl Mongers&lt;/a&gt; about it and expanded on one at last years &lt;a href="https://www.youtube.com/watch?v=9M1xZQ0_Skw&amp;amp;t=26s"&gt;London Perl Workshop&lt;/a&gt;. I love the language and I want more people using it.&lt;/p&gt;

&lt;p&gt;Things got interesting when the company that I work for &lt;a href="https://www.zpg.co.uk/careers"&gt;Zoopla&lt;/a&gt; decided to sponsor the event and I went from the role of speaker to that of company spokes person. I had a lot more conversations about what it was like to work at Zoopla (awesome) than I was expecting to have.&lt;/p&gt;

&lt;h4&gt;
  
  
  Day 1
&lt;/h4&gt;

&lt;p&gt;I arrived in Scotland on the Saturday before the conference but the first two days of workshops I skipped because I had other matters, involving my upcoming nuptials, to deal with. So I arrived on Wednesday not sure what to expect. I'd been to a couple of one day events over the years but not a full three day one. &lt;/p&gt;

&lt;p&gt;What I was reminded of was gaming conventions, these I've done a lot of, and the general feeling of a group of like minded people in one place really came across. One major difference between the modern gaming convention and the conference was the male to female ratio was still skewing highly to the male side, that and the lack of a significant child presence. But other than that it felt very similar including the social aspects, meeting up with people who you often only see at these sort of events. &lt;/p&gt;

&lt;p&gt;I attended a number of talks, some that I wasn't expecting because the schedule had got changed around and my calender wasn't up to date. Still interesting stuff on a variety of topics. One talk I found interesting was on &lt;a href="https://www.perlfoundation.org/"&gt;The Perl Foundation&lt;/a&gt; and what it does. I may have ended up volunteering to help manage one of the sites, more on that if it happens. Then I saw Curtis "Ovid" Poe's talk on Rescuing a Legacy codebase (that could also be titled, how to talk to the business). And I got to meet him after and thank him for his excellent talk on Perl6 that had got me interested in it. At the end of the day was the Lightning talks which seemed fun and I decided to write one for Thursday.&lt;/p&gt;

&lt;p&gt;Then it was off to &lt;a href="https://oran-mor.co.uk/"&gt;Òran Mór&lt;/a&gt; for the meal. There was wonderful food (though too many people like the haggis pakora for my liking, I was hoping for thirds). I may have drunk a wee bit too much. But it was a nice relaxing evening. &lt;/p&gt;

&lt;h4&gt;
  
  
  Day 2
&lt;/h4&gt;

&lt;p&gt;So Thursday was a bit blurry, I have felt worse but I didn't have enough sleep and was mostly existing on coffee and painkillers. Still I chatted to a bunch of people saw some interesting talks and wrote a little lightning talk.&lt;/p&gt;

&lt;p&gt;Then it was time for my talk, I'd been preparing it for a while and had given it once internally to be able to get feedback and I felt I could manage to cover a lot about &lt;a href="https://www.slideshare.net/SimonProctor8/perl6-signatures-types-and-multicall"&gt;Perl6 Method Calls&lt;/a&gt;. I will admit to feeling some pressure as Larry Wall was sitting at the back of the room. But he's a very nice guy and I got to thank him for inventing the language that got me back into coding. So that was nice. We ended up at a lot of talks together as I mostly was on the unofficial Perl6 track. &lt;/p&gt;

&lt;p&gt;As I say, the day was a bit of a blur, but I did give another Lightning Talk (about Perl6 operators) at the end of the day and then ended up talking to a few people about working at Zoopla and Perl6 so it was all good.&lt;/p&gt;

&lt;h4&gt;
  
  
  Day 3
&lt;/h4&gt;

&lt;p&gt;By Friday I was having a combination of lack of sleep, way too much nervous energy and general buzz. I saw some great talks and there are more I didn't see. My current plan is as the talks get released on You Tube I'll link to them.&lt;/p&gt;

&lt;h4&gt;
  
  
  Thoughts
&lt;/h4&gt;

&lt;p&gt;All in all I had a great time, though I'm going to need to learn to pace myself better. I'm not as young as I was and keeping up that level of enthusiasm has somewhat drained me. &lt;/p&gt;

&lt;p&gt;Still I'd definitely recommend next years &lt;a href="https://www.facebook.com/tpconf.eu/"&gt;European Perl Conference in Riga&lt;/a&gt; (facebook link there, main site coming soon). And if you're in the UK the upcoming &lt;a href="http://act.yapc.eu/lpw2018/"&gt;London Perl Workshop&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;And if you're not into Perl (either version)? Well there's lots of other conferences. Find one for what you are interested in, and why not give a talk. It's easier than it looks. Find a thing you know about, preferably something you're passionate about, make some slides and practice some patter.&lt;/p&gt;

&lt;p&gt;Also if you're not interested in Perl (especially Perl6) hang around. I plan on getting more things written here about it. &lt;/p&gt;

</description>
      <category>perl5</category>
      <category>perl6</category>
      <category>perl</category>
      <category>conference</category>
    </item>
  </channel>
</rss>
