/now
projects
ramblings
smol projects

function times 3

23.11.2023 2 min read

Create a function that takes three collections of arguments and returns the sum of the product of numbers. Add the result of the first digit in each collection multiplied together to the result of the second digit in each collection multiplied together to get the final solution.

product(1,2)(1,1)(2,3) ➞ 8
// 1 * 1 * 2 + 2 * 1 * 3
product(10,2)(5,0)(2,3) ➞ 100
// 10 * 5 * 2 + 2 * 0 * 3
product(1,2)(2,3)(3,4) ➞ 30
// 1 * 2 * 3 + 2 * 3 * 4
product(1,2)(0,3)(3,0) ➞ 0
// 1 * 0 * 3 + 2 * 3 * 0

Well, turns out we can’t do this in Crystal. Trying to define a def in a def will lead to an error: Can't define def inside def. The closest we’re going to get is through the use of multiple procs:

def product(x : Int32, y : Int32)
  return ->(a : Int32, b : Int32) {
    return ->(c : Int32, d : Int32) {
      return x * a * c + y * b * d
    }
  }
end
a = product(1, 2)
b = a.call(1, 1)
c = b.call(2, 3)
puts c

Which is to say, not close at all, but it’s something.

Nim:

func product(a: int, b: int): proc =
    proc(c: int, d: int): proc =
        proc (e: int, f: int): int =
            a * c * e + b * d * f

echo product(1, 2)(1, 1)(2, 3)

So, +1 to Nim this time round.

Raku:

sub product($a, $b) {
    sub inner($c, $d) {
        sub last($e, $f) {
            return $a * $c * $e + $b * $d * $f;
        }
    }
}

say product(1, 2)(1, 1)(2, 3)

It works just fine in Raku too.

Last one for completion’s sake:

function product(a: number, b: number) {
  return function (c: number, d: number) {
    return function (e: number, f: number) {
      return a * c * e + b * d * f;
    };
  };
}

console.log(product(1, 2)(1, 1)(2, 3));
Built with Astro and Tailwind 🚀