Perl weekly challenge 096 - Raku

This is a Raku answer for the 096 Perl Weekly Challenge


Exercise 1

The first task consists in writing a script to reverse the order of words without leading/trailing spaces. These are the examples:

Example 1:
Input: $S = "The Weekly Challenge"
Output: "Challenge Weekly The"

Example 2:
Input: $S = " Perl and Raku are part of the same family "
Output: "family same the of part are Raku and Perl"

This is easy to implement in Raku due to the many routines and methods included by default:

sub challenge( $string ) {
  return $string.words.reverse;

Exercise 2

The second exercise is the implementation of the Wagner–Fischer algorithm to compute the edit distance between two strings of characters. Raku shows the muscle of its support for OOP, allowing to almost literally write down the algorithm as a class. This is the pseudocode algorithm on Wikipedia:

function LevenshteinDistance(char s[1..m], char t[1..n]):
  declare int d[0..m, 0..n]
  set each element in d to zero
  for i from 1 to m:
      d[i, 0] := i
  for j from 1 to n:
      d[0, j] := j
  for j from 1 to n:
      for i from 1 to m:
          if s[i] = t[j]:
            substitutionCost := 0
            substitutionCost := 1
          d[i, j] := minimum(d[i-1, j] + 1,                   // deletion
                             d[i, j-1] + 1,                   // insertion
                             d[i-1, j-1] + substitutionCost)  // substitution
  return d[m, n]

And the definition of the class in Raku:

class Distance {

  has Str $.s1;
  has Str $.s2;

  method distance() {
    return $!s1.chars if $!s2.chars == 0;
    return $!s2.chars if $!s1.chars == 0;
    min ( s1 => $!s1.chop, s2 => $!s2      ).distance + 1, s1 => $!s1     , s2 => $!s2.chop ).distance + 1, s1 => $!s1.chop, s2 => $!s2.chop ).distance + 
!($!s1.substr(*-1) eq $!s2.substr(*-1)).Num; # substitution

While this may be similar to the other dynamic programming solutions provided, this OOP recursion appears more intuitive and readable for neophytes like me. It has been quite amazing to be able to write the class definition and see that it works!

Leave a comment

About Mimosin

user-pic I teach on Social Psychology and have fun in my spare time coding in Raku. "The past is written, the future is left for us to code"