<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Various and Sundry</title>
	<atom:link href="https://variousandsundry.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://variousandsundry.com</link>
	<description>An Assortment of Thoughts about Programming and More</description>
	<lastBuildDate>Sun, 12 Nov 2023 14:39:19 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=7.0</generator>
<site xmlns="com-wordpress:feed-additions:1">105783034</site>	<item>
		<title>&#8220;Missing Members&#8221;: The Live Blog</title>
		<link>https://variousandsundry.com/missing-members-the-live-blog/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=missing-members-the-live-blog</link>
		
		<dc:creator><![CDATA[augiedb]]></dc:creator>
		<pubDate>Sun, 12 Nov 2023 14:39:02 +0000</pubDate>
				<category><![CDATA[Weekly Challenge]]></category>
		<category><![CDATA[perl]]></category>
		<guid isPermaLink="false">https://variousandsundry.com/?p=220</guid>

					<description><![CDATA[This week's weekly challenge causes me to trip over an issue I saw in last week's Perl Weekly newsletter.  Great timing!]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">We&#8217;re back for week #242 of The Weekly Challenge.</p>



<p class="wp-block-paragraph">This week, I&#8217;m trying something different.  I&#8217;m going to work on my solution to the task through this blog and then copy-and-paste my solution into a terminal window to see if it works.  I&#8217;ll walk you through my process, think out loud, and maybe even hit the programming lottery and write something that works on the first try.</p>



<p class="wp-block-paragraph">Probably not, but <em>maybe</em>&#8230;</p>



<p class="wp-block-paragraph">Think of this as the blogging version of Twitch. Look over my shoulder as I figure things out&#8230;</p>



<h2 class="wp-block-heading">&#8220;Missing Members&#8221;</h2>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">You are given two arrays of integers.</p>



<p class="wp-block-paragraph">Write a script to find out the missing members in each other arrays.</p>
</blockquote>



<p class="wp-block-paragraph">The example given:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Input: @arr1 = (1, 2, 3)
       @arr2 = (2, 4, 6)
Output: (&#x5B;1, 3], &#x5B;4, 6])

(1, 2, 3) has 2 members (1, 3) missing in the array (2, 4, 6).
(2, 4, 6) has 2 members (4, 6) missing in the array (1, 2, 3).
</pre></div>


<p class="wp-block-paragraph">OK, that seems &#8220;easy&#8221; enough.  Most things that I think are &#8220;easy&#8221; to program often have a horrible complication in the second half that I never see coming, though.  </p>



<p class="wp-block-paragraph">That would make for an interesting blog post, at least.</p>



<p class="wp-block-paragraph">My first thought is that this is something that should just be brute forced.  Loop through the arrays, do something with the data, compare the data, print out the solution.</p>



<p class="wp-block-paragraph">I also think that it&#8217;s very likely there&#8217;s a module on CPAN that would make this program supremely simple to write.  There&#8217;s probably a two line solution to this there somehow.</p>



<p class="wp-block-paragraph">I also bet I could jump over to ChatGPT right now and get an answer. Maybe I&#8217;ll try that after my solution, for kicks.  The point of this programming exercise, though, is to practice skills, not prompts.</p>



<p class="wp-block-paragraph">Here&#8217;s my first idea:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: perl; title: ; notranslate">
my @arr1 = (1, 2, 3);
my @arr2 = (2, 4, 6);

my @missing_from_second;
my $match = 0;
foreach my $value_first( @arr1 ) {
  foreach my $value_second( @arr2 ) {
     $match++ if ($value_second == $value_first);
  }
  push(@missing_from_second, $value_first) if ($match == 0);
  $match = 0;
}
</pre></div>


<p class="wp-block-paragraph">We do a nested loop to compare all the values. If there&#8217;s a match, we essentially set a flag(<a href="#annotation1">*</a>).  If there&#8217;s no match, that means the number is missing in the second array and we add it to the results array.</p>



<p class="wp-block-paragraph">Is it elegant? Not really. Is it optimized?  Heck, no. I already see one or two things I could do to speed it up.  (Two ideas off the top of my head: Short circuiting as soon as a match is found.  Sorting the arrays first and short-circuiting once the loop has passed by the number.)</p>



<p class="wp-block-paragraph">This will only check the first case &#8212; how many values are in the first array that aren&#8217;t in the second?</p>



<p class="wp-block-paragraph">It loops over the first array and flags any time a value from there is in the second array as it loops over it.  If there is a match, that sets a flag which will cause the value NOT to be added to the list of missing values.</p>



<p class="wp-block-paragraph">Does it work?  I think it might.  Let&#8217;s write a quick output to check:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: perl; title: ; notranslate">
print &quot;Array 1 has &quot; . scalar(@missing_from_second) . &quot; members missing in Array 2\n&quot;;
</pre></div>


<p class="wp-block-paragraph">Now I&#8217;ll do a quick copy-and-paste and check it in the terminal window and run it:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
Array 1 has 2 members missing in Array 2
</pre></div>


<p class="wp-block-paragraph">That is correct. 1 and 3 are in the first array, but not the second. My code just worked on the first try.  </p>



<p class="wp-block-paragraph">Thanks for reading my blog.  I&#8217;m taking my Win and going home.</p>



<p class="wp-block-paragraph">OK, nevermind, I&#8217;ll see this all the way through.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Printing Out The Solution, Wherein the Perl Weekly Newsletter Saves My Bacon</h2>



<p class="wp-block-paragraph">How could we print that final message in a prettier way? We need to print out an array, which means I&#8217;ll just use my pretty printer from previous challenges:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: perl; title: ; notranslate">

sub pretty_print_array {

        my @array = @_;
        my $length = scalar @array;
        my $count = 1;

        print &quot;(&quot;;

        foreach my $value(@array) {
                print $value;
                print &quot;, &quot; if $count &lt; $length;
                $count++;
        }

        print &quot;)\n&quot;;

        return;
}

</pre></div>


<p class="wp-block-paragraph">Let&#8217;s integrate that:</p>



<pre class="wp-block-code"><code>print pretty_print_array(@arr1) . " has " . scalar( @missing_from_second ) . " members " . pretty_print_array(@missing_from_second) . " missing in the array " . pretty_print_array(@arr2) . "\n";</code></pre>



<p class="wp-block-paragraph">I&#8217;ve used that pretty_print_array a lot in recent challenges, but never as much as in this one line.  That gives us:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
(1, 2, 3)
(1, 3)
(2, 4, 6)
 has 2 members  missing in the array 
</pre></div>


<p class="wp-block-paragraph">That ain&#8217;t right.</p>



<p class="wp-block-paragraph">However, I immediately recognize the problem, since it was fresh in my mind.</p>



<p class="wp-block-paragraph">The reason for this wackiness was covered in a link from <a href="https://perlweekly.com/archive/641.html" target="_blank" rel="noopener">the Perl Weekly newsletter just last week</a>.  Check out <a href="https://www.reddit.com/r/perl/comments/17mkv4x/the_different_between_comma_and_period_in_print/" target="_blank" rel="noopener">this Reddit article discussing how the Perl print statement works</a>.  It explains everything in graphic detail.</p>



<p class="wp-block-paragraph">So I made this ugly-looking thing, instead &#8212;</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: perl; title: ; notranslate">
print pretty_print_array(@arr1);
print &quot; has &quot;;
print scalar( @missing_from_second ) . &quot; members &quot;;
print pretty_print_array(@missing_from_second);
print &quot; missing in the array &quot;;
print pretty_print_array(@arr2) , &quot;\n&quot;;

</pre></div>


<p class="wp-block-paragraph">&#8212; and it worked beautifully:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
(1, 2, 3) has 2 members (1, 3) missing in the array (2, 4, 6)
</pre></div>


<p class="wp-block-paragraph">I also had to remove the new line at the end of the pretty_print_array() function so everything would be together in a single line.</p>



<h2 class="wp-block-heading">Again, Functionalize All the Things!</h2>



<p class="wp-block-paragraph">That solves the problem for the first example, but what about the second? How can I structure this code to easily run as many times as I want without having to copy and paste code?  </p>



<p class="wp-block-paragraph">It&#8217;s time to Function-ify the code!  (I&#8217;m going to keep making up new verbs until I find one that I like&#8230;)</p>



<p class="wp-block-paragraph">This is where we&#8217;re starting from, minus the pretty_print_array() function:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: perl; title: ; notranslate">
my @arr1 = (1, 2, 3);
my @arr2 = (2, 4, 6);

my @missing_from_second;
my $match = 0;
foreach my $value_first( @arr1 ) {
  foreach my $value_second( @arr2 ) {
     $match++ if ($value_second == $value_first);
  }
  push(@missing_from_second, $value_first) if ($match == 0);
  $match = 0;
}

print pretty_print_array(@arr1);
print &quot; has &quot;;
print scalar( @missing_from_second ) . &quot; members &quot;;
print pretty_print_array(@missing_from_second);
print &quot; missing in the array &quot;;
print pretty_print_array(@arr2) , &quot;\n&quot;;
</pre></div>


<p class="wp-block-paragraph">This should be simple enough.  I&#8217;m going to make one big function out of the whole thing and then call it with the arrays as the parameters.  I would normally separate the print part out at the end into its own statement, but then I&#8217;m passing along four different arrays.  I don&#8217;t want to do that for a simple piece of code like this.</p>



<p class="wp-block-paragraph">So let&#8217;s see the final code with calls from both examples:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: perl; title: ; notranslate">
my @arr1 = (1,2,3);
my @arr2 = (2,4,6);
find_missing_members( \@arr1, \@arr2 );

@arr1 = (1, 2, 3, 3);
@arr2 = (1, 1, 2, 2);
find_missing_members( \@arr1, \@arr2 );

sub find_missing_members {

  my @arr1 = @{ shift() };
  my @arr2 = @{ shift() };

  my @missing_from_second;
  my $match = 0;
  foreach my $value_first( @arr1 ) {
    foreach my $value_second( @arr2 ) {
      $match++ if ($value_second == $value_first);
    }
  push(@missing_from_second, $value_first) if ($match == 0);
  $match = 0;
  }

  print pretty_print_array(@arr1);
  print &quot; has &quot;;
  print scalar( @missing_from_second ) . &quot; members &quot;;
  print pretty_print_array(@missing_from_second); 
  print &quot; missing in the array &quot;; 
  print pretty_print_array(@arr2) , &quot;\n&quot;;
}

</pre></div>


<h2 class="wp-block-heading">Turning This Car Around</h2>



<p class="wp-block-paragraph">That works, BUT!  I just realized that I haven&#8217;t done the comparison in reverse order.  We know which members of @arr1 are missing in @arr2, but we don&#8217;t yet know which members of @arr2 are missing in @arr1!</p>



<p class="wp-block-paragraph">I have to admit that I had a moment here where, in my head, I wondered about how I might functionalize the first half of find_missing_members() further to make a generic comparison and then send the arrays in different orders.  Or what if I had to &#8212; gulp &#8212; copy and paste the nested loop to do it again in the other order?</p>



<p class="wp-block-paragraph">That&#8217;s when dummy me realized the much simpler solution: Call the same function I already have, but reverse the order of the arrays I&#8217;m sending in:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: perl; title: ; notranslate">
my @arr1 = (1,2,3);
my @arr2 = (2,4,6);
find_missing_members( \@arr1, \@arr2 );
find_missing_members( \@arr2, \@arr1 );

@arr1 = (1, 2, 3, 3);
@arr2 = (1, 1, 2, 2);
find_missing_members( \@arr1, \@arr2 );
find_missing_members( \@arr2, \@arr1 );
</pre></div>


<p class="wp-block-paragraph">That gives you the answer from the challenge write-up:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: plain; title: ; notranslate">
(1, 2, 3) has 2 members (1, 3) missing in the array (2, 4, 6)
(2, 4, 6) has 2 members (4, 6) missing in the array (1, 2, 3)
(1, 2, 3, 3) has 2 members (3, 3) missing in the array (1, 1, 2, 2)
(1, 1, 2, 2) has 0 members () missing in the array (1, 2, 3, 3)
</pre></div>


<h2 class="wp-block-heading">Rewrite the Whole Thing? Optimize?</h2>



<p class="wp-block-paragraph">Like I said at the top, this is a brute force solution. Nested loops seem a little much.  That means with two 3-value arrays, we go through the loop 9 times.</p>



<p class="wp-block-paragraph">What if we only had to go through the loop once, and we set up a hash to carry the set of unique values in the second array?  Even populating that hash by looping over one array once, we&#8217;ll cut down the number of loops from 9 to 3 + 3, or 6.</p>



<p class="wp-block-paragraph">Like so:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: perl; title: ; notranslate">
  my @missing_from_second;
  my %second_values;
  map{ $second_values{$_} = 1; } @arr2;

  foreach my $first_value( @arr1 ) {
    push(@missing_from_second, $first_value) if !$second_values{$first_value};
  }
</pre></div>


<p class="wp-block-paragraph">The one bit of trickiness we have here is that we&#8217;re hashing the second array, then looping over the first.  That&#8217;s the correct order to do things. Then we loop over the first array and look for each value as a key in the hash of the second.  This means only one comparison per iteration of the loop.</p>



<p class="wp-block-paragraph">In the first set of input data, that changes the total iterations from 9 to 6.  In the second set of data with 4-item arrays, we go from 16 down to 8.</p>



<p class="wp-block-paragraph">If we had two 100 item arrays, this would cut us back from 10,000 iterations down to 200.</p>



<p class="wp-block-paragraph">It doesn&#8217;t seem like a big difference with the smaller numbers, but the savings pile up quickly.</p>



<p class="wp-block-paragraph">On the other hand, the nested loops thing feels easier to read.  There&#8217;s less thinking to do when you&#8217;re reading it to understand what&#8217;s going on.  So long as the arrays don&#8217;t grow ridiculously big, will those extra steps really be an issue?  Computers are pretty fast these days.  Am I being <em>too</em> clever?</p>



<p class="wp-block-paragraph">On the other, other hand, I like the way I constructed this loop.  I love how readable it actually is with the if after the push.  (&#8220;Push the value onto the missing list if it doesn&#8217;t exist in the hash.&#8221;)</p>



<p class="wp-block-paragraph">It would also work as a second map statement:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: perl; title: ; notranslate">
map{ $second_values{$_} = 1; } @arr2;
map{ push(@missing_from_second, $_) if !$second_values($_);  } @arr1;

</pre></div>


<p class="wp-block-paragraph">Now it&#8217;s a one-liner loop that matches the map used to turn the other array into a hash.    </p>



<p class="wp-block-paragraph">Wait, if we&#8217;re talking functional programming and that whole second loop there is to filter out a list into an array, shouldn&#8217;t we just use grep{} ?!?</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: perl; title: ; notranslate">
map{ $second_values{$_} = 1; } @arr2;

@missing_from_second = grep{
  !$second_values{$_};
} @arr1;
</pre></div>


<p class="wp-block-paragraph">For some, I have no doubt we&#8217;re getting even less readable now.  However, as a functional programmer wannabe, I love this solution.  We ditch the push() command, an if statement, and the foreach() loop and replace it with a grep{} function.</p>



<p class="wp-block-paragraph">Variable naming also counts here.  With this grep we filter just to the values that don&#8217;t exist and put them in an array with &#8220;missing&#8221; in its name. That helps guide the mind in the right direction.</p>



<p class="wp-block-paragraph">This is also where I get a little frustrated by Perl, because I know other languages have a built-in command to determine if a value is present in an array. Javascript has includes() as an Array method.  Python has an &#8220;in&#8221; command that will work.  Elixir has &#8220;Enum.member?&#8221; as well as an &#8220;in&#8221; thing of its own.  Perl has grep(), but it feels weird to grep() inside a grep{}.</p>



<p class="wp-block-paragraph">Also, under the hood, I&#8217;m sure those other languages are just going a similar thing. (<a href="#annotation2">**</a>)</p>



<p class="wp-block-paragraph">I&#8217;m 100% sure there&#8217;s a module on CPAN that will do this for me, but I try to stick to core Perl as much as possible.  (Honestly, it&#8217;s easier at work to use everything built-in than having to fill out a form to get permission to use a new module from the legal and security teams&#8230;)</p>



<h2 class="wp-block-heading">Ask ChatGPT</h2>



<p class="wp-block-paragraph">As promised near the top of this post, I ran the challenge through ChatGPT, which did a better job of printing out the answer and keeping everything in bite-sized chunks. </p>



<p class="wp-block-paragraph">However, at the core of things, we were fairly close with our functional thinking:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: perl; title: ; notranslate">
my @missing_in_arr1 = grep { my $num = $_; !grep { $_ == $num } @$arr2 } @$arr1;
my @missing_in_arr2 = grep { my $num = $_; !grep { $_ == $num } @$arr1 } @$arr2;
</pre></div>


<p class="wp-block-paragraph">I like my solution better.  It doesn&#8217;t work as hard to fit everything into one line, which gives the answer room to breathe and be more easily understandable.  It essentially does the same thing, but that&#8217;s a lot of stuff on each line in there.</p>



<p class="wp-block-paragraph">Also, the ChatGPT solution checks in both directions inside the same function. I prefer having one function and calling it twice, just with different parameters.(<a href="#annotation3">***</a>)</p>



<h2 class="wp-block-heading">Annotations</h2>



<p class="wp-block-paragraph" id="annotation1">(*) I just realized that back in college, we&#8217;d call these &#8220;sentinels.&#8221;  I haven&#8217;t heard that term since. Everyone has called them &#8220;flags&#8221; ever since.  </p>



<p class="wp-block-paragraph" id="annotation2">(**) I looked up <a href="https://github.com/elixir-lang/elixir/blob/v1.12.3/lib/elixir/lib/enum.ex#L1879" target="_blank" rel="noopener">the source code for Enum.is_member in Elixir</a>.  It&#8217;s a reduce function using some underlying Erlang code, of course:</p>


<div class="wp-block-syntaxhighlighter-code "><pre class="brush: erlang; title: ; notranslate">
{:error, module} -&gt;
        module.reduce(enumerable, {:cont, false}, fn
          v, _ when v === element -&gt; {:halt, true}
          _, _ -&gt; {:cont, false}
        end)
        |&gt; elem(1)
</pre></div>


<p class="wp-block-paragraph" id="annotation3">(***) I&#8217;m running out of time to publish this, so I&#8217;m not going to go look up the difference between parameters and arguments at the moment. Please forgive me if I got it backwards here.  I&#8217;ll do better next time.</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">220</post-id>	</item>
		<item>
		<title>An Attempt to Simplify Fails, But Works</title>
		<link>https://variousandsundry.com/an-attempt-to-simplify-fails-but-works/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=an-attempt-to-simplify-fails-but-works</link>
		
		<dc:creator><![CDATA[augiedb]]></dc:creator>
		<pubDate>Sun, 29 Oct 2023 03:42:51 +0000</pubDate>
				<category><![CDATA[Weekly Challenge]]></category>
		<category><![CDATA[perl]]></category>
		<guid isPermaLink="false">https://variousandsundry.com/?p=196</guid>

					<description><![CDATA[Two relatively easy challenges result in simple responses that still take up too much space.]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">The two new challenges in <a href="https://theweeklychallenge.org/blog/perl-weekly-challenge-240/" target="_blank" rel="noopener">The Weekly Challenge #240</a> are pretty straightforward.  It&#8217;s spelled right out for you in the instructions.  Read it carefully and the code writes itself.</p>



<p class="wp-block-paragraph">This was the perfect week to try to simplify my Perl code.  I&#8217;ve said previously that I&#8217;m no Perl Golfer, but maybe this is the week to create a one-liner solution.  In both challenges, the heart of the answer is, indeed, one line long.</p>



<p class="wp-block-paragraph">But then I go and mess everything up by making the script run both samples from the challenge and pretty print everything out to the screen.  Suddenly, a one-line script has three subroutines and 57 lines supporting the one that does the actual work.  </p>



<p class="wp-block-paragraph">Sorry, I just spoiled Challenge #2.  </p>



<h2 class="wp-block-heading">&#8220;Acronym&#8221;</h2>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">You are given an array of strings and a check string.</p>



<p class="wp-block-paragraph">Write a script to find out if the check string is the acronym of the words in the given array.</p>
</blockquote>



<p class="wp-block-paragraph">In other words, grab the first letter of each word, smash them together, and see if the resulting string is equal to the check string.  In my mind, I see a substr() call and a join() and bob&#8217;s my uncle.</p>



<p class="wp-block-paragraph">I added a ternary, a map{}. and a loc() to fill it all out.  </p>



<p class="wp-block-paragraph">Here&#8217;s the variable set-up and the single line of code you need to solve this one:</p>



<pre class="wp-block-code"><code>my @string = ("Perl", "Python", "Pascal");
my $chk = "ppp";

print $chk eq join('', map { lc( substr($_, 0, 1) ) } @string ) ? "True" : "False";</code></pre>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">Yes, the pipe operator in Elixir would make this prettier. It&#8217;s slightly frustrating to read this from the inside out, but it&#8217;s not that hard. I&#8217;ve grown used to it from years of experience.</p>



<ul class="wp-block-list">
<li class="">Map over the string</li>



<li class="">Grab the first letter of each word</li>



<li class="">Convert it to lower case.</li>



<li class="">Smash the letters into one big string.</li>



<li class="">Compare that string to the check string and print out whether they&#8217;re the same.</li>
</ul>



<p class="wp-block-paragraph">I know it&#8217;s a bit controversial and you shouldn&#8217;t use it that much, but <strong>I love the $_ in Perl</strong>.  Yes, it is dangerous and if you&#8217;re not careful you might get unexpected results.  As with all programming, if you know what&#8217;s happening, the magic isn&#8217;t so magical. It&#8217;s only useful.  </p>



<p class="wp-block-paragraph"><strong>Only use the magic where appropriate and it&#8217;ll work <em>for</em> you, not <em>against</em> you</strong>.</p>



<p class="wp-block-paragraph">If there were multiple lines inside the map{} function there, I&#8217;d turn $_ into a named variable with something that describes better what it is.  For a one-liner like this, that&#8217;s not a problem. </p>



<p class="wp-block-paragraph">If we exploded out that one-liner into a series of steps, it would look something like this:</p>



<pre class="wp-block-code"><code>my @firsts = map{ substr($_, 0, 1) } @string;

my $str_compare = join('', @firsts);

$str_compare = lc($str_compare);

if ($str_compare eq $chk) {
    print "True";
} else {
    print "False";
}
</code></pre>



<p class="wp-block-paragraph">The important thing to note here is that <strong>Perl&#8217;s lowercase function will lowercase the entire word</strong>.  You don&#8217;t need to pass each individual letter through the lc() function to get the desired results.  Logically, though, I like the way it reads.  I changed it for the exploded example, but kept the lc() call per-character in my main solution.</p>



<p class="wp-block-paragraph">There&#8217;s not much more to it than that, so let&#8217;s go to the second challenge.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">&#8220;Build Array&#8221;</h2>



<p class="wp-block-paragraph">I&#8217;ll be honest, I stared at this challenge for a long time before I understood it.  Thank goodness for the examples given in the write-up:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">You are given an array of integers.</p>



<p class="wp-block-paragraph">Write a script to create an array such that new[i] = old[old[i]] where 0 &lt;= i &lt; new.length.</p>
</blockquote>



<p class="wp-block-paragraph">Basically, loop over the old array.  The first position&#8217;s value will tell you the position in the old array whose value you want to put in the first position of the new array.  Then, you walk straight down the line and fill out the rest of the array.</p>



<p class="wp-block-paragraph">The simple solution is this:</p>



<pre class="wp-block-code"><code>@new = map{ $old&#91;$_] } @old;</code></pre>



<p class="wp-block-paragraph">I built everything else up around that.  I made a main() and re-used the pretty_print_array() from an earlier challenge, though I did need to modify it to accept an array and not a reference to an array. I suppose there&#8217;s a lesson here about not bothering to send a reference to an array when it&#8217;s just a one parameter thing.</p>



<p class="wp-block-paragraph">I&#8217;ll throw the whole thing in here next, but then I&#8217;m calling it a week.</p>



<p class="wp-block-paragraph">Happy coding!</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-code"><code>#!/usr/bin/perl
use strict;
use warnings;

main( (0, 2, 1, 5, 3, 4) );
print "\n";
main( (5, 0, 1, 2, 3, 4) );


sub main {

    my @int = @_;

    print "Input: ";
    pretty_print_array( @int );
    print "Output: ";
    pretty_print_array( build_array( @int ) );

}



sub build_array {

    my @int = @_;

    return map{ $int&#91;$_] } @int;

}


sub pretty_print_array {

    ## I copied-and-pasted this from my solution for Task 1.
    ## If I copy-and-paste it again, by law I need to turn
    ## it into a library. ;-)

        my @array = @_;
        my $length = scalar @array;
        my $count = 1;

        print "(";

        foreach my $value(@array) {
                print $value;
                print ", " if $count &lt; $length;
                $count++;
        }

        print ")\n";

        return;
}</code></pre>



<p class="wp-block-paragraph">That&#8217;s a lot of boilerplate for a one line piece of code, isn&#8217;t it?</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">196</post-id>	</item>
		<item>
		<title>&#8220;Same String&#8221; Part Deux: Now In Javascript and Python</title>
		<link>https://variousandsundry.com/same-string-part-deux-now-in-javascript-and-python/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=same-string-part-deux-now-in-javascript-and-python</link>
		
		<dc:creator><![CDATA[augiedb]]></dc:creator>
		<pubDate>Mon, 23 Oct 2023 02:01:00 +0000</pubDate>
				<category><![CDATA[Weekly Challenge]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[python]]></category>
		<guid isPermaLink="false">https://variousandsundry.com/?p=170</guid>

					<description><![CDATA[Having done the challenge in Perl and Elixir, the author dives head long into Python and Javascript to find further differences and language craziness.]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">Once <a href="https://variousandsundry.com/same-string-lets-functionalize-this-one/">I created a formula with Perl and Elixir</a> to solve <a href="https://theweeklychallenge.org/blog/perl-weekly-challenge-239/" target="_blank" rel="noopener">this week&#8217;s Weekly Challenge,</a> it was easy to run with it in Javascript and Python.  It&#8217;s mostly a matter of changing the syntax.  Yet, I still mixed things up a bit as I went along.</p>



<h2 class="wp-block-heading">JavaScript Same String</h2>



<p class="wp-block-paragraph">Once again, I created a <em>main()</em> function like some kind of crazy C programmer just to have a function that can run each new set of arrays through the paces.</p>



<p class="wp-block-paragraph">Most of this should look familiar:</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-code"><code>// Same String

main(&#91;"ab", "c"], &#91;"a", "bc"]);
main(&#91;"ab", "c"], &#91;"ac", "b"]);
main(&#91;"ab", "cd", "e"], &#91;"abcde"]);


function main( arr1, arr2 ) {

    // 0
    console.log('Input 1:')
    console.log('@arr1 = (' + arr1 + ')')
    console.log('@arr2 = (' + arr2 + ')')

    // 1
    const arr1_string = combine_list(arr1)
    const arr2_string = combine_list(arr2)

    const result = compare_strings(arr1_string, arr2_string)

    console.log('Output: ' + result)
    console.log('')

}

// 2
function combine_list( arr ) {
    return arr.reduce((acc, str) =&gt; acc + str)
}

// 3
function compare_strings( str1, str2 ) {
    return ( str1 == str2 ) ? true : false
}
</code></pre>



<p class="wp-block-paragraph">0. I&#8217;m following the exercise writeup in prepending the array name with an encircled &#8220;A&#8221; to indicate it&#8217;s an array.  Perl type checking, baby!<em> I regret nothing.</em></p>



<p class="wp-block-paragraph">1. I went back and forth on whether I should store the results of this function into a new variable and then use that as the arguments in the function on the next line.  You could just as easily put this short function call inside the parenthesis in the <em>compare_strings()</em> call and be done with it.</p>



<p class="wp-block-paragraph">I just thought this way of reading the code was a little easier, so I did it this way.</p>



<p class="wp-block-paragraph">2. The reducer function is inside a function all its own.  I thought it looked ugly to inline that function twice in <em>main()</em>, so it went to the side on its own.  <strong>I love a good reducer. </strong> You just pass the item you&#8217;re iterating over with the accumulator, itself, and a function to do the dirty work. <em>Voila!</em></p>



<p class="wp-block-paragraph">3. Yes!  A ternary operator!  Come at me.  I&#8217;m fine with it.  A lot of people hate ternaries, but there&#8217;s nothing wrong with them when used right.  This is a prime example of &#8220;right.&#8221;  It only gets ugly when you have a complicated &#8220;if&#8221; statement or you start nesting ternaries, but for a simple true/false test like this, it makes perfect sense.  <a href="https://variousandsundry.com/same-string-lets-functionalize-this-one/">I didn&#8217;t need one in Elixir</a> because I was using pattern matching.  I used it as an option in Perl, but I should have committed to it.  Maybe I&#8217;ll go back and fix the script on Github&#8230;</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">&#8220;Same String&#8221; Simplified: Python Edition</h2>



<p class="wp-block-paragraph">I&#8217;m forcing myself to learn Python, because I need it for work.  With a few tweaks, it&#8217;s just Perl/Ruby/Javascript with white space that counts.  I keep bouncing between languages and forgetting which ones use [] for arrays/lists versus ().  Also, this is the fourth version of this code I&#8217;ve written, so maybe I&#8217;m just getting tired?</p>



<p class="wp-block-paragraph">The good news is, Python does have a built-in reducer function, but you do need to import it from a core library.  I know Perl has things like this, too, but it&#8217;s always happening for me in Python.  I&#8217;m always having to import something from a core library to use in my scripts, and that feels clunky.</p>



<p class="wp-block-paragraph">I get it &#8212; why waste memory on lots of libraries if you don&#8217;t need them, but can&#8217;t the language automatically include them when it seems they are being used?  It&#8217;s still better than having to install them, but it does annoy me.</p>



<p class="wp-block-paragraph">Let&#8217;s get right to the code:<br></p>



<pre class="wp-block-code"><code>from functools import reduce

def show_inputs(arr1, arr2):
    print( "Input: @arr1 = ", arr1 )
    print( "       @arr2 = ", arr2 )


def reduce_string(arr):
    return reduce(lambda x, y: x + y, arr)

## 1
def compare_strings(str1, str2):
    return "true" if str1 == str2 else "false"

def show_output(final_answer):
    print( "Output: ", final_answer, "\n" )

## 2
def run_everything(arr1, arr2):
    show_inputs(arr1, arr2)
    str1 = reduce_string(arr1) ## 3
    str2 = reduce_string(arr2)
    show_output( compare_strings(str1, str2) )

## Run process with example data
run_everything(&#91;"ab", "c"], &#91;"a", "bc"] )
run_everything(&#91;"ab", "c"], &#91;"ac", "b"] )
run_everything(&#91;"ab", "cd", "e"], &#91;"abcde"] )
</code></pre>



<p class="wp-block-paragraph">I like how compact this code feels. It&#8217;s very thin.  It gets straight to the point and doesn&#8217;t waste a lot of space.  The reduce function with the lambda will take some getting used to, but it does the job.</p>



<ol class="wp-block-list">
<li class="">You can display a boolean in Python in a print statement by using the <em>str()</em> function.  But why bother when, for the sake of this exercise, I just need a string to print out?  That&#8217;s why I&#8217;m returning the string here instead of the Boolean.  Note that booleans in Python start with a capital letter, but my strings here do not.</li>



<li class="">Is there a Pep yet for a pipe operator?  That might clean some of this up.</li>



<li class="">Since there is no pipeline operator, there&#8217;s really no reason to call a single function with two arrays to get back a tuple or an array of two arrays back, right?  So I call directly into the reducer here, instead of the middle step of having a function do that twice.</li>
</ol>



<p class="wp-block-paragraph">It is also at about this point that I realized my quest to finish the first challenge in four different languages means I never did the second challenge of the week.</p>



<p class="wp-block-paragraph">Better luck next week, me!</p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">170</post-id>	</item>
		<item>
		<title>&#8220;Same String&#8221;: Let&#8217;s Functionalize the #$%@# Out of This One</title>
		<link>https://variousandsundry.com/same-string-lets-functionalize-this-one/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=same-string-lets-functionalize-this-one</link>
					<comments>https://variousandsundry.com/same-string-lets-functionalize-this-one/#comments</comments>
		
		<dc:creator><![CDATA[augiedb]]></dc:creator>
		<pubDate>Mon, 23 Oct 2023 01:43:52 +0000</pubDate>
				<category><![CDATA[Weekly Challenge]]></category>
		<category><![CDATA[elixir]]></category>
		<category><![CDATA[perl]]></category>
		<guid isPermaLink="false">https://variousandsundry.com/?p=151</guid>

					<description><![CDATA[I wrote a Perl script that feels so functional that it was super simple to rewrite it even better in Elixir.]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This is a <a href="https://theweeklychallenge.org/blog/perl-weekly-challenge-239/" target="_blank" rel="noopener">The Weekly Challenge #239</a>.  An exercise.  Practice.</p>



<p class="wp-block-paragraph">There&#8217;s a fine line between Best Practices and Let&#8217;s Push This As Far As We Can.</p>



<p class="wp-block-paragraph">To be honest, I&#8217;m still not sure if I went too far with this one, or <em>not far enough.</em></p>



<p class="wp-block-paragraph">This is an exercise that&#8217;s made for Perl.  It&#8217;s string manipulation. It&#8217;s perfect for the Practical Extraction and Report Language.  As I wrote it, though, I also noticed that <strong>it&#8217;s a great bit of functional coding</strong> &#8212; extract the data, transform it into something else, and report the results.  Use a series of functions to morph the beginning data into the end data you want.</p>



<p class="wp-block-paragraph">That meant that I had to do it in Elixir, also.</p>



<p class="wp-block-paragraph">I thought I&#8217;d just write the Perl script and then transform it into Elixir, but then things took on a life of their own.</p>



<h2 class="wp-block-heading">&#8220;Same String&#8221;: Perl Edition</h2>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">You are given two arrays of strings.</p>



<p class="wp-block-paragraph">Write a script to find out if the word created by concatenating the array elements is the same.</p>
</blockquote>



<p class="wp-block-paragraph">For example, is an array of &#8220;ab&#8221; and &#8220;c&#8221; the same as &#8220;a&#8221; and &#8220;bc&#8221; after their parts have been smashed together?  Yes, both are &#8220;abc&#8221;.</p>



<p class="wp-block-paragraph">You could program this straight through. Wouldn&#8217;t need a single subroutine in the code at all.  For the purposes of testing this, though, I put everything into a main() that we could call with all three sets of arrays provided in the challenge.  And I re-used my <a href="https://variousandsundry.com/running-sum-or-i-love-recursion/" data-type="post" data-id="75">pretty_print_array() subroutine from the last challenge</a>.</p>



<p class="wp-block-paragraph">Here&#8217;s the code to run the first test, minus pretty_print_array() which you can find in last week&#8217;s writeup at the link in the last paragraph:</p>



<pre class="wp-block-code"><code>
my @arr1 = ("ab", "c");
my @arr2 = ("a", "bc");
main(\@arr1, \@arr2);

sub main {

    my @arr1 = @{ shift() };
    my @arr2 = @{ shift() };

    print 'Input: @arr1 = ' . ( pretty_print_array(\@arr1) ) . "\n";
    print 'Input: @arr2 = ' . ( pretty_print_array(\@arr2) ) . "\n";

    my $combined_string1 = '';
    my $combined_string2 = '';

    map{ $combined_string1 .= $_; } @arr1;
    map{ $combined_string2 .= $_; } @arr2;

    print "Output: ";

    if (  $combined_string1 eq $combined_string2 ) {
        print "true\n";
    } else {
        print "false\n";
    }

}</code></pre>



<p class="wp-block-paragraph">Is it elegant and reusable and the kind of thing I&#8217;d put up on CPAN?  Nah.</p>



<p class="wp-block-paragraph">Does it solve the challenge?  Yes.</p>



<p class="wp-block-paragraph">However, I saw what was happening here:</p>



<ul class="wp-block-list">
<li class="">Print the array to the screen</li>



<li class="">Combine the parts of the arrays into strings</li>



<li class="">Compare those two strings I just created.</li>



<li class="">Print out the results of that comparison</li>
</ul>



<p class="wp-block-paragraph">One bullet point basically feeds into the next. We&#8217;re taking a piece of data, transforming it in some way, and then sending it to the next step to transform it again and pass it along.  </p>



<p class="wp-block-paragraph">This is perfect for <a href="https://thinkingelixir.com/course/code-flow/module-1/pipe-operator/" target="_blank" rel="noopener">Elixir&#8217;s pipe operator</a>.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">More Functions, More Fun</h2>



<p class="wp-block-paragraph">First, though, let&#8217;s functionalist the &amp;$%# out of this in Perl:</p>



<pre class="wp-block-code"><code>
#!/usr/bin/perl
use warnings;
use strict;

my @arr1 = ("ab", "c");
my @arr2 = ("a", "bc");
main(\@arr1, \@arr2);

sub main {

    my @arr1 = @{ shift() };
    my @arr2 = @{ shift() };

    show_inputs(\@arr1, \@arr2);
    my $combined1 = combine_arrays(\@arr1);
    my $combined2 = combine_arrays(\@arr2);
    my $results = compare_strings($combined1, $combined2);
    show_output( $results );

}

sub show_inputs {

    my @arr1 = @{ shift() };
    my @arr2 = @{ shift() };

    print "Input: \@arr1 = " . ( pretty_print_array(\@arr1) ) . "\n";
    print "Input: \@arr2 = " . ( pretty_print_array(\@arr2) ) . "\n";

    return;

}

sub show_output {

    my $final_results = shift();
    print "Output: " . $final_results . "\n\n";

}


sub combine_arrays {

    my @arr = @{ shift() };
    my $combined_string = '';
    map{ $combined_string .= $_; } @arr;

    return $combined_string;
}

sub compare_strings {

    my ($str1, $str2) = @_;

    return 'true' if  $str1 eq $str2;
    return 'false';

    # Or, in ternary fashion:
    # return $str eq $str2 ? "true" : "false";


}

</code></pre>



<p class="wp-block-paragraph">This will work whether there is one value in each array, or an insanely large number that fits in memory.  It&#8217;s still only going to work with two arrays, but I&#8217;m not going to worry about that bit of craziness.</p>



<p class="wp-block-paragraph">But each step from that bullet point list I wrote out above is now solved with a subroutine.  One feeds into the next.  Send data in, get data in, pass that new data onto the next one.  Some of it is purely functional and some of it is just for displaying information to the screen.</p>



<p class="wp-block-paragraph">Here&#8217;s how it breaks down:</p>



<ul class="wp-block-list">
<li class="">Print the array to the screen ( <em>show_inputs() </em>)</li>



<li class="">Combine the parts of the arrays into strings ( <em>combine_arrays()</em> )</li>



<li class="">Compare the strings ( <em>compare_strings()</em> )</li>



<li class="">Print out the results of that comparison ( <em>show_output()</em> )</li>
</ul>



<p class="wp-block-paragraph">It&#8217;s also super easy to test this now.  Every step can be tested independently.</p>



<p class="wp-block-paragraph">This kind of programming of chaining functions together and letting one feed the next is the perfect program to write in a functional language. Let&#8217;s look at this in Elixir.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">&#8220;Same String&#8221;: Elixir Edition</h2>



<p class="wp-block-paragraph">Take the same bullet points.  Run a data point through them.  See what happens.</p>



<p class="wp-block-paragraph">I&#8217;ll create a module named SameString to put all the functions in.  I&#8217;ll start with the brains behind the whole operation and then add the individual functions above it as we go.</p>



<pre class="wp-block-code"><code>
defmodule SameString do

    def run_everything(tuple_of_lists) do

        tuple_of_lists
        |&gt; show_inputs()
        |&gt; combine_lists()
        |&gt; compare_strings()
        |&gt; show_output()

    end
end</code></pre>



<p class="wp-block-paragraph">That might look a little familiar already.  I did a little renaming, since Elixir uses lists instead of arrays, but it&#8217;s the same function (née subroutine) names.</p>



<p class="wp-block-paragraph">If you&#8217;re not familiar with Elixir, I&#8217;ll try to explain how the pipe operator works:  The expression or output of the function just before it is passed as the first argument to the function after it.  I&#8217;ve constructed these functions to only require one parameter, so you never have to see anything besides the function names.  The output of <em>tuple_of_lists/1</em> is sent directly into <em>show_inputs</em>/1, then the output from that function is sent as the first argument to the next function, <em>combine_lists/1</em>, etc.</p>



<p class="wp-block-paragraph">The pipe operator is super cool.  <strong>The only other Elixir feature in the core language that comes close is pattern matching.</strong>  We&#8217;ll be using that, too.  Stick around.</p>



<p class="wp-block-paragraph">To make this more concrete, here&#8217;s how we&#8217;ll be calling this function:</p>



<pre class="wp-block-code"><code>SameString.run_everything( {&#91;"ab", "c"], &#91;"a", "bc"]} )</code></pre>



<p class="wp-block-paragraph">The data structure I&#8217;ve chosen is a tuple with two lists in it.  You could just as easily make it a list of two lists, but I liked adding in an extra data structure for the exercise of it all. </p>



<p class="wp-block-paragraph">The <em>run_everything/1</em> function receives it as tuple_of_lists and then pipes it into show_inputs.  As you might imagine, that function shows the inputs to the screen:</p>



<pre class="wp-block-code"><code>   def show_inputs({list1, list2}) do
        IO.puts "Input: List1 = "
        IO.inspect list1

        IO.puts "Input: List2 = "
        IO.inspect list2

        {list1, list2}
    end
</code></pre>



<p class="wp-block-paragraph">Three things to look out for here:  I&#8217;m cheating a bit by returning the tuple of lists back out of this function so we can continue the pipe chain.</p>



<p class="wp-block-paragraph">Second, in my attempt to be descriptive of the function by listing out the parameters the function takes, I&#8217;ve created a pattern-matching element.  If I tried to pass in a single string or a number or even a map, this function would never run and the whole program would die then and there.  Anything other than a tuple (indicated with curly braces) with two variables of some kind in it will fail to match and this function would never run.</p>



<p class="wp-block-paragraph">Third, you need to use IO.inspect to print out an array, rather than IO.puts.  It&#8217;s a long story, but trust me on that one.</p>



<p class="wp-block-paragraph">From there, the tuple of lists gets passed to the next function:</p>



<pre class="wp-block-code"><code>def combine_lists({list1, list2}) do

        string1 = reduce_string(list1)
        string2 = reduce_string(list2)

        {string1, string2}

end
</code></pre>



<p class="wp-block-paragraph">Here&#8217;s where things shift a bit from Perl.  Rather than mapping over the array and concatenating the pieces into a string, <strong>I want to run a reducer</strong> to boil the array down to one long string.</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-code"><code>    def reduce_string( list_of_strings ) do

        Enum.reduce(list_of_strings, "", fn characters, acc -&gt;
            acc &lt;&gt; characters
        end)

    end</code></pre>



<p class="wp-block-paragraph">This takes each element of the array and concatenates it to an accumulator.  <em>Enum.reduce</em> naturally returns that last generated value.</p>



<p class="wp-block-paragraph">And then <em>combine_lists/1</em> sends back out a tuple of the two new strings.</p>



<p class="wp-block-paragraph">The pipe operator neatly sends that tuple over to<em> compare_strings/1</em>. If you&#8217;re not used to pattern matching, this is where things get interesting.  There are two different functions named <em>compare_strings/1</em> here:</p>



<pre class="wp-block-code"><code>    def compare_strings({string1, string1}) do
        true
    end

    def compare_strings({_, _}) do
        false
    end
</code></pre>



<p class="wp-block-paragraph"><strong>Elixir is doing pattern matching.</strong>  If the two values inside the tuple being passed into the function are the same, it returns true. Otherwise, it returns false.  </p>



<p class="wp-block-paragraph">In the second function, you replace the parameters with underscores to indicate that you&#8217;re not going to do anything with the values that are coming in here. Elixir is serious about this &#8211; it&#8217;ll give you a warning if you run the script with named variables you never use.  </p>



<p class="wp-block-paragraph">There&#8217;s one more way to shorten this up even more:</p>



<pre class="wp-block-code"><code>
    def compare_strings({string1, string1}), do: true
    def compare_strings({_, _}), do: false</code></pre>



<p class="wp-block-paragraph">Slightly different syntax, but it&#8217;s well-suited for the one-liner structure for short functions.</p>



<p class="wp-block-paragraph">That true or false value then gets passed into <em>show_output/1</em>, and I&#8217;ll do some one-liners and pattern matching here, too:</p>



<pre class="wp-block-code"><code>    def show_output(true), do: IO.puts "Output: True"
    def show_output(false), do: IO.puts "Output: False"</code></pre>



<p class="wp-block-paragraph">Part of the fun of Elixir is writing complete programs without ever touching an if statement.  Use pattern matching and the rest will follow.</p>



<p class="wp-block-paragraph">And done. That&#8217;s the end of the pipeline. </p>



<p class="wp-block-paragraph">It&#8217;s a nifty bit of code that feels right, reads easily, and (again) could be easily tested.</p>



<p class="wp-block-paragraph">To see the final script, check out my Github repo.</p>



<p class="wp-block-paragraph">But, wait!  Let&#8217;s program this in two more languages!  Stay tuned&#8230;.</p>



<h2 class="wp-block-heading">Other Solutions</h2>



<p class="wp-block-paragraph">I&#8217;m not good at <a href="http://wiki.c2.com/?PerlGolf" target="_blank" rel="noopener">Perl Golf</a>.  It&#8217;s not something I&#8217;ve practiced or worked on, either, but it&#8217;s always entertaining to watch someone who is skilled at it. Check out <a href="http://wiki.c2.com/?PerlGolf" target="_blank" rel="noopener">W. Luis Mochán&#8217;s one-liner solution</a> on his blog.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://variousandsundry.com/same-string-lets-functionalize-this-one/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">151</post-id>	</item>
		<item>
		<title>Recursive Running Sum Redux &#8211; In Elixir! 🏃‍♂️</title>
		<link>https://variousandsundry.com/recursive-running-sum-redux-in-elixir/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=recursive-running-sum-redux-in-elixir</link>
					<comments>https://variousandsundry.com/recursive-running-sum-redux-in-elixir/#comments</comments>
		
		<dc:creator><![CDATA[augiedb]]></dc:creator>
		<pubDate>Sat, 14 Oct 2023 20:23:46 +0000</pubDate>
				<category><![CDATA[Weekly Challenge]]></category>
		<category><![CDATA[elixir]]></category>
		<guid isPermaLink="false">https://variousandsundry.com/?p=103</guid>

					<description><![CDATA[Elixir makes for the cleanest and best solution to the Running Sum problem.  But should I go with two parameters or three?]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph"><em>Previously, on Various And Sundry</em>: I wrote <a href="https://variousandsundry.com/running-sum-or-i-love-recursion/">a Perl script to calculate the running sum of an array</a>.  It used recursion.</p>



<p class="wp-block-paragraph"><em>Recursion</em>? I love recursion! And you know what else I love?  <strong>Elixir</strong>!  So let&#8217;s solve the Weekly Challenge in Elixir next!</p>



<h2 class="wp-block-heading">Elixir: A Prelude</h2>



<p class="wp-block-paragraph">It&#8217;s worthy of another essay entirely, but <strong>I love Elixir. </strong></p>



<p class="wp-block-paragraph">I don&#8217;t use it regularly.  In fact, it had been years since I wrote a line of Elixir code before sitting down to write this script. I had to breeze through some documentation first to jog my memory of the syntax.</p>



<p class="wp-block-paragraph">As a functional language, Elixir screams out to solve this challenge in a quick, logical, and readable way.</p>



<p class="wp-block-paragraph">Let&#8217;s get to it.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Short But Sweet</h2>



<p class="wp-block-paragraph">I got my B.A. in Computer Science in college.  I took one class that used a functional language, and that was Scheme.  I remember little of that class besides that we coded aspects of the board game, Clue, as our programming projects.  (Oh, and all the parenthesis!)  The lessons learned in writing recursive functions always stuck around.</p>



<p class="wp-block-paragraph">The number one rule: <strong>The recursive equation will continue until it hits its base case.</strong>  Never forget the base case, and you&#8217;ll have a <em>chance</em> to be successful.  </p>



<p class="wp-block-paragraph">An accumulator often helps, too.</p>



<p class="wp-block-paragraph">As a reminder, <a href="https://theweeklychallenge.org/blog/perl-weekly-challenge-237/" target="_blank" rel="noopener">the challenge for Running Sum</a> is this:</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">Write a script to return the running sum of the given array. The running sum can be calculated as sum[i] = num[0] + num[1] + …. + num[i].</p>
</blockquote>



<p class="wp-block-paragraph">As an example, the array (1, 1, 1, 1, 1) will return (1, 2, 3, 4, 5).</p>



<p class="wp-block-paragraph">(I&#8217;ll bounce back and forth between <em>array</em> and <em>list</em> here.  The challenge is written with Perl in mind, so that&#8217;s an array. This solution is in Elixir, which uses lists. We don&#8217;t need to nit-pick on this point, for the purposes of this exercise.)</p>



<p class="wp-block-paragraph">I&#8217;ll jump straight to my code:</p>



<pre class="wp-block-code"><code>defmodule Runner do

    def running_sum(&#91;head | tail], new_list, sum) do
        sum = sum + head
        running_sum(tail, new_list ++ &#91;sum], sum)
    end

    def running_sum(&#91;], new_list, _) do
        new_list
    end
end</code></pre>



<p class="wp-block-paragraph">Super simple: Pass in the full array ( (1, 1, 1, 1, 1) in the example above) along with the new list (which starts empty) and the running total (which starts as 0).  </p>



<p class="wp-block-paragraph">When that first list is empty, return the new list.  The end.</p>



<p class="wp-block-paragraph"><strong>Elixir&#8217;s pattern matching is a whole different way to think about functions</strong> if you&#8217;re used to the kind of functions you use in scripting languages like Perl, Python, Javascript, Ruby, etc.  It&#8217;s such a cool feature that they&#8217;re all working on implementing it.  (Raku included it in the language.)</p>



<p class="wp-block-paragraph">The same goes for the pipeline operator in Elixir, which I didn&#8217;t have a use for with this challenge. Maybe next time!</p>



<p class="wp-block-paragraph">Also, you&#8217;ll notice this line:</p>



<pre class="wp-block-code"><code>sum = sum + head</code></pre>



<p class="wp-block-paragraph">I said in a previous write-up that <a href="https://variousandsundry.com/running-sum-or-i-love-recursion/">I love a good += operator</a>, so why didn&#8217;t I use it here?  Elixir doesn&#8217;t have it.  It&#8217;s an immutable language.  The equals symbol doesn&#8217;t exactly work the way you think it does.  There&#8217;s a re-binding thing going on here and a pattern-matching thing happening and &#8212;  I&#8217;m not the right person to explain it all.  Just trust me on this.</p>



<p class="wp-block-paragraph">Also, I could avoid this entire explanation by moving that line into the parameters of the running_sum/3 call on the next line and not assigning it to anything:</p>



<pre class="wp-block-code"><code>running_sum(tail, new_list ++ &#91;sum + head], sum + head)</code></pre>



<p class="wp-block-paragraph">I just hate that duplication.  There&#8217;s a way around it entirely that we&#8217;ll explore two sections from now, though.  Keep scrolling down!</p>



<h2 class="wp-block-heading">Let It Run!</h2>



<p class="wp-block-paragraph">I ran the three examples given in the challenge with this bit of copy-and-past brilliance:</p>



<pre class="wp-block-code"><code>IO.puts 'Exercise 1: '
list_of_numbers = &#91;1, 2, 3, 4, 5]
IO.inspect list_of_numbers
IO.inspect Runner.running_sum(list_of_numbers, &#91;], 0)

IO.puts 'Exercise 2: '
list_of_numbers = &#91;1, 1, 1, 1, 1]
IO.inspect list_of_numbers
IO.inspect Runner.running_sum(list_of_numbers, &#91;], 0)

IO.puts 'Exercise 3: '
list_of_numbers = &#91;0, -1, 1, 2]
IO.inspect list_of_numbers
IO.inspect Runner.running_sum(list_of_numbers, &#91;], 0)</code></pre>



<p class="wp-block-paragraph">Note that <strong>I&#8217;m using IO.inspect to print out the list.</strong>  For very good reasons, IO.puts doesn&#8217;t work here for what we want.  It translates the numbers into character codes and makes a mess of things. It&#8217;s a common gotcha for new Elixirists. ( And for those who haven&#8217;t written it in a while, as it turns out.)</p>



<p class="wp-block-paragraph">That produces the following results:</p>



<pre class="wp-block-code"><code>Exercise 1: 
&#91;1, 2, 3, 4, 5]
&#91;1, 3, 6, 10, 15]
Exercise 2: 
&#91;1, 1, 1, 1, 1]
&#91;1, 2, 3, 4, 5]
Exercise 3: 
&#91;0, -1, 1, 2]
&#91;0, -1, 0, 2]
</code></pre>



<p class="wp-block-paragraph">Works for me! Short, but sweet.</p>



<h2 class="wp-block-heading">Wait!  Can We Do It Another Way?</h2>



<p class="wp-block-paragraph">It bothered me that I had to set so much stuff up.  I had to pass in a blank array<em> and</em> a starting sum of 0 to kick things off.  Could I rewrite this with only 2 parameters to the function?</p>



<p class="wp-block-paragraph">Yes, it&#8217;s possible. However, I don&#8217;t like the solution. I&#8217;m curious what you think.</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-code"><code>defmodule Runner do

    ## First iteration
    def running_sum(&#91;head | tail], &#91;]) do
        running_sum(tail, &#91;head])
    end

    ## Everything inbetween
    def running_sum(&#91;head | tail], new_list) do
        new_list = new_list ++ &#91;head + List.last(new_list)]
        running_sum(tail, new_list)
    end

    ## Base Case
    def running_sum(&#91;], new_list) do
        new_list
    end

end

IO.puts 'Exercise 1: '
list_of_numbers = &#91;1, 2, 3, 4, 5]
IO.inspect Runner.running_sum(list_of_numbers, &#91;])</code></pre>



<p class="wp-block-paragraph">We end up with three functions (with an arity of 2 now) to handle the job.  The base case happens when the initial list has been drained dry.  Nothing changes there.</p>



<p class="wp-block-paragraph">But there is now a starting function. When the accumulator (new_list) is passed in as empty, the first function is kicked off.  It calculates the sum by adding the first value (head) from whatever is left of the initial list to the latest value in the new_list.  Then, it adds that to the end of new_list.</p>



<p class="wp-block-paragraph">Intellectually, this makes more sense to me.  It lets the functions do the work. It doesn&#8217;t require an extra parameter to be around. I never have to reassign the sum variable in the middle of a function.</p>



<p class="wp-block-paragraph">But it also seems like more work.  That long line in the second function takes too long to break down and understand for a first-time reader of the code.</p>



<p class="wp-block-paragraph">I prefer the tradeoff of one extra value to kick things off to the &#8220;simplicity&#8221; of a function/2 over a function/3.</p>



<p class="wp-block-paragraph">I only submitted running_sum/3 in the end.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">The Weekly Challenge Meta Note</h2>



<p class="wp-block-paragraph">I doubt I&#8217;m the first person to do a Weekly Challenge in Elixir.  I see the stats include &#8220;Erlang&#8221; solutions, but I&#8217;m not sure if that&#8217;s a catch-all for both Elixir and Erlang.</p>



<p class="wp-block-paragraph">I think I&#8217;ll be doing more in Elixir in any case, just to keep my functional mind sharp.</p>



<p class="wp-block-paragraph"><a href="https://github.com/augiedb/perlweeklychallenge-club/blob/new-branch/challenge-238/augiedb/elixir/ch-1.exs" target="_blank" rel="noopener">You can find the full script from this challenge on Github.</a></p>



<p class="wp-block-paragraph"><br><br><br><br></p>
]]></content:encoded>
					
					<wfw:commentRss>https://variousandsundry.com/recursive-running-sum-redux-in-elixir/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">103</post-id>	</item>
		<item>
		<title>Persistence Sort, In Which I Give Up and Use a Global 🌎</title>
		<link>https://variousandsundry.com/persistence-sort-in-which-i-give-up-and-use-a-global/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=persistence-sort-in-which-i-give-up-and-use-a-global</link>
					<comments>https://variousandsundry.com/persistence-sort-in-which-i-give-up-and-use-a-global/#comments</comments>
		
		<dc:creator><![CDATA[augiedb]]></dc:creator>
		<pubDate>Sat, 14 Oct 2023 19:41:42 +0000</pubDate>
				<category><![CDATA[Weekly Challenge]]></category>
		<category><![CDATA[perl]]></category>
		<guid isPermaLink="false">https://variousandsundry.com/?p=84</guid>

					<description><![CDATA[An attempt to write a persistence sort ends in a global variable, but also recursion!  You take the good with the bad...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">This is the second half of <a href="https://theweeklychallenge.org/blog/perl-weekly-challenge-238/" target="_blank" rel="noopener">Week 238 in the Weekly Challenge</a>.  Previously, I programmed <a href="https://variousandsundry.com/running-sum-or-i-love-recursion/">a running sum in Perl</a> that wasn&#8217;t that difficult at all.  I spent more time on cleaning things up and writing a pretty printer function so it looked good on the screen when it ran.</p>



<p class="wp-block-paragraph">Today, things get real.  We&#8217;re talking recursion, global variables, and nested sorting.  </p>



<p class="wp-block-paragraph">Whoa, boy.</p>



<h2 class="wp-block-heading">Part Two:  Sort For Your Life!</h2>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p class="wp-block-paragraph">You are given an array of positive integers. Write a script to sort the given array in increasing order with respect to the count of steps required to obtain a single-digit number by multiplying its digits recursively for each array element. If any two numbers have the same count of steps, then print the smaller number first.</p>
</blockquote>



<p class="wp-block-paragraph">To truly understand this one, <a href="https://theweeklychallenge.org/blog/perl-weekly-challenge-238/" target="_blank" rel="noopener">you need to see the examples</a>.  At least, I did.</p>



<p class="wp-block-paragraph">This was one of those cases where a simple sort command wasn&#8217;t going to work.  I&#8217;d have to sort by a custom function.  Fine, let&#8217;s do that.</p>



<p class="wp-block-paragraph">The solution I came up with was to first create a hash that stores the number of times the digits in a number need to be multiplied together to get to a single-digit number.  </p>



<pre class="wp-block-code"><code>sub multiply_numbers_recursively {

    # Recursion Rocks

    my $number = shift();
    my $count  = shift();

    my @list_of_numbers = split(//, $number);
    return $count if scalar(@list_of_numbers) == 1;

    my $running_total = 1;
    map{ $running_total *= $_ } @list_of_numbers;

    return multiply_numbers_recursively($running_total, ++$count);
}

<p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo; min-height: 20px;"></p></code></pre>



<p class="wp-block-paragraph">Ah, the glories of recursion!  In my last write-up, I mentioned how much I love map{} and grep{}, but recursion is right up there, too.  </p>



<p class="wp-block-paragraph">This function keeps multiplying until you get down to the number you need, tracking the number of iterations in an accumulator named $count.  </p>



<p class="wp-block-paragraph">I split the number as if it were a string of characters to get a list of numbers.  I went with &#8220;//&#8221;, but you can also use &#8216;undef&#8217; or an empty string like &#8221; there to do the same thing.</p>



<p class="wp-block-paragraph">Having created this hash with all the information I need, I can run my custom sort and arrange the numbers in the correct order: first, by the number of multiplications, and secondarily in increasing value of the numbers. </p>



<pre class="wp-block-code"><code>sub persistence_sort {

    my @array = @{ shift() };

    foreach my $value( @array ) {
        my @array_of_numbers = split(//, $value);
        $steps{$value} = multiply_numbers_recursively($value, 0);
    }

    my @final_results = sort compare keys %steps;

    return @final_results;

}

sub compare {

    ## The two level sort function
    ## The reason I have a global variable.

    if($steps{$a} &lt; $steps{$b}) {
        return -1;
    } elsif ($steps{$a} == $steps{$b}) {
        return 1 if $a &gt; $b;
        return -1;
    } else {
        return 1
    }

}</code></pre>



<p class="wp-block-paragraph">persistence_sort() loops over the positive integers in the array that the program is given.  It runs multiply_numbers_recursively() to do all the multiplying necessary of the individual digits in a number until their sum is less than 10.  The number of rounds it took to get there is stored in the %steps hash.</p>



<p class="wp-block-paragraph">Now, you can sort the keys of the hash by (1) how many rounds of multiplication it took and then, when the number of loops is equal for multiple values, (2) how big the original number is.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Gasp! The Horrors!</h2>



<p class="wp-block-paragraph">There is one ugly bit of business that this solution has, though.  <strong>A global variable.</strong>  %steps has to be global for this to work.  I ran out of time to try to work it out with that.  I have a feeling there&#8217;s a way to pass %steps into the sort that will make things get very ugly very quickly.  Or, I&#8217;d have to include the sort function directly inside the sort command line.</p>



<p class="wp-block-paragraph">Finally, I copied-and-pasted that pretty printer from the last exercise, wrote a bit of script to loop over the two sample arrays, and got back these results:</p>



<pre class="wp-block-code"><code>BEFORE: (15, 99, 1, 34)
AFTER: (1, 15, 34, 99)

BEFORE: (50, 25, 33, 22)
AFTER: (22, 33, 50, 25)</code></pre>



<p class="wp-block-paragraph">That&#8217;s nothing too fancy, but it gets the job done.</p>



<p class="wp-block-paragraph">Again, the global variable bites back as I had to make sure to blank that out after each iteration:</p>



<pre class="wp-block-code"><code>## Test Values:
my @first  = (15, 99, 1, 34);
my @second = (50, 25, 33, 22);
my @tests = ( \@first, \@second );

## Runner:
foreach my $array_ref( @tests ) {

    print "BEFORE: ";
    pretty_print_array( $array_ref);

    my @results = persistence_sort( $array_ref );

    print "AFTER: ";
    pretty_print_array(\@results);

    print "\n";

    ## The price I pay for the global
    %steps = ();

}
</code></pre>



<p class="wp-block-paragraph">When I didn&#8217;t restart the hash, it would continue to add in all the values from the next test.  It sorts it correctly, at least, but that&#8217;s not what I was trying to do.</p>



<p class="wp-block-paragraph">Next week, I&#8217;ll follow this up by using a GOTO statement!</p>



<p class="wp-block-paragraph"><a href="https://github.com/augiedb/perlweeklychallenge-club/blob/new-branch/challenge-238/augiedb/perl/ch-2.pl" target="_blank" rel="noopener">You can find my final script on Github.</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://variousandsundry.com/persistence-sort-in-which-i-give-up-and-use-a-global/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">84</post-id>	</item>
		<item>
		<title>Running Sum, or &#8220;I ♥️ Recursion&#8221;</title>
		<link>https://variousandsundry.com/running-sum-or-i-love-recursion/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=running-sum-or-i-love-recursion</link>
					<comments>https://variousandsundry.com/running-sum-or-i-love-recursion/#comments</comments>
		
		<dc:creator><![CDATA[augiedb]]></dc:creator>
		<pubDate>Sat, 14 Oct 2023 19:41:11 +0000</pubDate>
				<category><![CDATA[Weekly Challenge]]></category>
		<category><![CDATA[perl]]></category>
		<guid isPermaLink="false">https://variousandsundry.com/?p=75</guid>

					<description><![CDATA[In which the author starts The Weekly Challenge with a simple recursive algorithm to provide a running sum of an array.  And then goes overboard...]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph"><a href="https://theweeklychallenge.org" target="_blank" rel="noopener">The Weekly Challenge began as a Perl-focused exercise</a> but has since expanded to let any and all languages in.  It&#8217;s still mostly Perl, but I&#8217;ll be using it as an avenue to explore other languages, as well.</p>



<h2 class="wp-block-heading">Running Sum</h2>



<p class="wp-block-paragraph">This week&#8217;s challenge is to write a script that takes an array and outputs an array where each value is a sum of the numbers before it.</p>



<p class="wp-block-paragraph">For example:</p>



<pre class="wp-block-code"><code>Input: (1, 2, 3, 4, 5)
Output: (1, 3, 6, 10, 15)</code></pre>



<p class="wp-block-paragraph">This one is fairly straightforward.  You can loop right over it and add the numbers as you go pretty quickly:</p>



<p class="wp-block-paragraph"></p>



<pre class="wp-block-code"><code><p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo;"><span style="font-variant-ligatures: no-common-ligatures">use Data::Dumper</span> qw/Dumper/;</p><p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo; min-height: 20px;"></p><p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo;"><span style="font-variant-ligatures: no-common-ligatures">my @array = (1, 2, 3, 4, 5);</span></p>
<p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo;"><span style="font-variant-ligatures: no-common-ligatures"></span><span style="font-variant-ligatures: no-common-ligatures">my $sum = 0;</span></p><p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo; min-height: 20px;"></p><p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo;"><span style="font-variant-ligatures: no-common-ligatures">my @sum_array = map{ $sum += $_; } @array;</span></p><p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo; min-height: 20px;"></p><p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo;"><span style="font-variant-ligatures: no-common-ligatures">print Dumper \@sum_array;</span></p>

</code></pre>



<p class="wp-block-paragraph"><strong>That&#8217;s pretty simple, I think. </strong> I also have a &#8220;use strict&#8221; and &#8220;use warnings&#8221; bit at the top, but didn&#8217;t think it was necessary for this presentation.</p>



<p class="wp-block-paragraph"><strong>The variable names are pretty direct</strong>, also.  In a real world scenario, I wouldn&#8217;t name an array @array, but in a challenge like this, it&#8217;s fine.</p>



<p class="wp-block-paragraph"><strong>I love using Data::Dumper</strong> to easily print out all kinds of variables in Perl, but especially hashes of hashes and arrays of hashes and all that second level kind of craziness.</p>



<p class="wp-block-paragraph">I spent just enough time learning functional programming to take <strong>any excuse to use map{} or grep{} </strong>in Perl.  In my first version of this script, I was updating @sum_array inside the map statement.  Then I realized how silly that was.  If you&#8217;re mapping over something, the map command will produce a new array &#8212; just capture that!</p>



<p class="wp-block-paragraph">There is some advice out there about not using map in place of a for or foreach loop.  It&#8217;s meant as a data filter. I don&#8217;t always follow that advice, but I try to.  That&#8217;s what I did here.</p>



<p class="wp-block-paragraph"><strong>Two related hills I&#8217;ll die on</strong>: Don&#8217;t take the increment/decrement counter away from me, and let me have &#8220;+=&#8221; and &#8220;*=&#8221; and all the rest.  It always throws me off when a language doesn&#8217;t have that.</p>



<p class="wp-block-paragraph"></p>



<h2 class="wp-block-heading">Refactor for Prettiness</h2>



<p class="wp-block-paragraph">Having solved the issue, I took the challenge literally.  Data::Dumper doesn&#8217;t print out an array like this:</p>



<pre class="wp-block-code"><code>(1, 3, 6, 10, 15)</code></pre>



<p class="wp-block-paragraph"><br>It shows it like this:</p>



<pre class="wp-block-code"><code><p style="margin-right: 0px; margin-bottom: 0px; margin-left: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo;"><span style="font-variant-ligatures: no-common-ligatures">$VAR1 = &#91;</span></p>
<p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo;"><span style="font-variant-ligatures: no-common-ligatures">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1,</span></p>
<p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo;"><span style="font-variant-ligatures: no-common-ligatures">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3,</span></p>
<p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo;"><span style="font-variant-ligatures: no-common-ligatures">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 6,</span></p>
<p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo;"><span style="font-variant-ligatures: no-common-ligatures">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 10,</span></p>
<p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo;"><span style="font-variant-ligatures: no-common-ligatures">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 15</span></p>
<p style="margin: 0px; font-stretch: normal; font-size: 17px; line-height: normal; font-family: Menlo;"><span style="font-variant-ligatures: no-common-ligatures">&nbsp; &nbsp; &nbsp; &nbsp; ]</span>;<span style="font-variant-ligatures: no-common-ligatures"></span></p>
</code></pre>



<p class="wp-block-paragraph"><strong>So I had to create a prettier printer</strong>. While I&#8217;m sure there are a hundred good Perl modules I could download from CPAN to do it, I wanted to code something myself for this challenge.</p>



<p class="wp-block-paragraph">That&#8217;s how I ended up with this code at the end, including a bit of code to run all three examples from the challenge:</p>



<pre class="wp-block-code"><code>
# Test Data:
my @test1 = (1, 2, 3, 4, 5);
my @test2 = (1, 1, 1, 1, 1);
my @test3 = (0, -1, 1, 2);
my @array_examples = (\@test1, \@test2, \@test3);


print "Running Sum Code Results:\n";
print "=========================\n\n";

foreach my $array_ref (@array_examples) {

    print "Array: " ;
    pretty_print_array( $array_ref );

    my @results = show_running_sum($array_ref);

    print "Results: ";
    pretty_print_array(\@results);
   
    print "\n";

}

##
## Subroutines
##

sub show_running_sum {

    ## Ultimately, this is the heart of the solution

    my @array = @{ shift() };
    my $sum = 0;

    return map{ $sum += $_ } @array;

}

sub pretty_print_array {

        ## Total overkill, but I'm new and over-enthusiastic.
        ## In reality, I'd find something on CPAN for this.


        my @array = @{ shift() };
        my $length = scalar @array;
        my $count = 1;

        print "(";

        foreach my $value(@array) {
                print $value;
                print ", " if $count &lt; $length;
                $count++;
        }

        print ")\n";

        return;
}
</code></pre>



<p class="wp-block-paragraph">Turns out, making the final output look prettier took more coding than the challenge, itself.  Such is life sometimes&#8230;</p>



<p class="wp-block-paragraph">I&#8217;m also sure there are shorter, less readable ways to do it. I&#8217;ll take this way.  I&#8217;ll take readability over Perl Golf, though I do enjoy those efforts.</p>



<p class="wp-block-paragraph">Putting everything in new neat subroutines makes testing easier, also, though I didn&#8217;t test for this example. I&#8217;m sure I&#8217;ll do some TDD in a future weekly challenge, though.</p>



<p class="wp-block-paragraph"><a href="https://github.com/augiedb/perlweeklychallenge-club/blob/new-branch/challenge-238/augiedb/perl/ch-1.pl" target="_blank" rel="noopener">You can find the full script on my Github.</a></p>



<p class="wp-block-paragraph"><a href="https://variousandsundry.com/recursive-running-sum-redux-in-elixir/">I also solved this challenge in Elixir</a>, in case you are functionally-curious.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://variousandsundry.com/running-sum-or-i-love-recursion/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">75</post-id>	</item>
		<item>
		<title>Hypocrisy and Typed Languages: A Perl-ish Rant</title>
		<link>https://variousandsundry.com/hypocrisy-and-typed-languages-a-perl-ish-rant/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hypocrisy-and-typed-languages-a-perl-ish-rant</link>
		
		<dc:creator><![CDATA[augiedb]]></dc:creator>
		<pubDate>Fri, 07 Jul 2023 01:46:42 +0000</pubDate>
				<category><![CDATA[Perl]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[perl]]></category>
		<category><![CDATA[python]]></category>
		<category><![CDATA[types]]></category>
		<category><![CDATA[typescript]]></category>
		<guid isPermaLink="false">https://variousandsundry.com/?p=11</guid>

					<description><![CDATA[Do people really want typed languages?  And, hey, look who was out front on this one!]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">The latest rage in programming is types. <em>Everything</em> needs to be typed.</p>



<figure class="wp-block-image size-full"><img data-recalc-dims="1" fetchpriority="high" decoding="async" width="593" height="421" src="https://i0.wp.com/variousandsundry.com/wp-content/uploads/2022/04/6ce3oq.jpg?resize=593%2C421&#038;ssl=1" alt="Let's Type All the Things" class="wp-image-14" srcset="https://i0.wp.com/variousandsundry.com/wp-content/uploads/2022/04/6ce3oq.jpg?w=593&amp;ssl=1 593w, https://i0.wp.com/variousandsundry.com/wp-content/uploads/2022/04/6ce3oq.jpg?resize=300%2C213&amp;ssl=1 300w" sizes="(max-width: 593px) 100vw, 593px" /></figure>



<p class="wp-block-paragraph">If it wasn&#8217;t built that way, then they&#8217;ll graft something on to the language to confuse newbies and help some users pretend like they&#8217;re typing their language.  In reality, they&#8217;re just making Visual Studio Code happy.  </p>



<p class="wp-block-paragraph">Or they&#8217;ll create a new language that compiles down or transpiles to the original language, which leads to the creation of new build processes and increased waits and more annoyances.</p>



<p class="wp-block-paragraph">Hello, TypeScript, whose users really just want better autocomplete.</p>



<p class="wp-block-paragraph">At the same time, Perl is a reviled language that nailed types from the offset. A <strong>s</strong>calar variable is preceded by an s-looking &#8220;$&#8221;, an <strong>a</strong>rray is preceded by an a-looking &#8220;@&#8221;, and a <strong>h</strong>ash gets the &#8220;%&#8221; which is a slight reach, but is still H-looking enough.  If you&#8217;re looking at one item in that array, you refer to it as a scalar with an &#8220;$&#8221;.</p>



<p class="wp-block-paragraph">You don&#8217;t need Visual Studio Code to help you figure out what &#8220;@items&#8221; is, because it&#8217;s right there in the name.</p>



<p class="wp-block-paragraph">It&#8217;s basic typing in the language.  If you use the wrong sigil, you get the wrong results or an error message.</p>



<p class="wp-block-paragraph">And everyone called it unreadable and laughed at it.</p>



<p class="wp-block-paragraph">You hypocrites.</p>



<p class="wp-block-paragraph">In reality, it was just thirty years ahead of its time.</p>



<p class="wp-block-paragraph">Javascript is scrambling to figure out how best to add all of Typescript into the core language.  Ruby bolted something on a couple of years ago.  Elixir just announced that it&#8217;s starting to add types.</p>



<p class="wp-block-paragraph">Even the amazing and nigh-perfect Python skipped that typing step and is now scrambling to add one in somewhere, somehow. I should submit a Pep suggesting a &#8220;$&#8221; prefix for string types, but that leaves Sets without the obvious prefix. Lists can have the &#8220;£&#8221; character, which means it&#8217;ll be easier for British programmers to type. I&#8217;ll let someone else figure out Dictionary and Tuple types.</p>



<h2 class="wp-block-heading">TLDR</h2>



<p class="wp-block-paragraph">Types are mostly important to make Visual Studio Code handier.  Perl continues to set the standard other languages strive for, even while being the subject of all the barbs.  Welcome to my blog.</p>



<p class="wp-block-paragraph"></p>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">11</post-id>	</item>
	</channel>
</rss>
