Advent Calendar - December 7, 2019

Saturday, Dec 7, 2019| Tags: Perl, Raku

Advent Calendar 2019

| Day 6 | Day 7 | Day 8 |


The gift is presented by Jaldhar H. Vyas. Today he is talking about his solutions to Task #1: Ackermann Function of “The Weekly Challenge - 017”.

Create a script to demonstrate Ackermann function as defined in wikipedia.

As per the example in wiki page.


A(1, 2) = A(0, A(1, 1))
        = A(0, A(0, A(1, 0)))
        = A(0, A(0, A(0, 1)))
        = A(0, A(0, 2))
        = A(0, 3)
        = 4

This can be easily modeled by a recursive function with two special cases. (Plus an extra check to make sure the inputs are positive integers.) Here is the Perl version.


sub ackermann {
    my ($m, $n) = @_;

    if ($m < 0 || $n < 0) {
        return undef;
    }

    if ($m == 0) {
        return $n + 1;
    }

    if ($n == 0) {
        return ackermann($m - 1, 1);
    }

    return ackermann($m - 1, ackermann($m, $n - 1));
}

source code

In Raku, we can use the multi sub functionality for each case and parameter validation is built in.


multi sub ackermann (
    Int $m where { $m == 0 },
    Int $n where { $n >= 0 },
) {
    return $n + 1;
}

multi sub ackermann (
    Int $m where { $m >= 0 },
    Int $n where { $n == 0 },
) {
    return ackermann($m - 1, 1);
}

multi sub ackermann (
    Int $m where { $m >= 0 },
    Int $n where { $n >= 0 },
) {
    return ackermann($m - 1, ackermann($m, $n - 1));
}

source code



If you have any suggestion then please do share with us perlweeklychallenge@yahoo.com.

Advent Calendar 2019

SO WHAT DO YOU THINK ?

If you have any suggestions or ideas then please do share with us.

Contact with me