1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Perlでカリー化する関数を書いてみた

Last updated at Posted at 2013-02-17

タイトルのまま
書いてみた

#!/usr/bin/env perl
use 5.10.0;
use strict;
use warnings;

sub curry {
    my $func = shift;
    my $argc = shift;
    my @arg1 = @_;

    return sub {
        my @arg2 = @_;
        if(scalar(@arg1) + scalar(@arg2) >= $argc){
            return &$func(@arg1, @arg2);
        }
        return curry($func, $argc, @arg1, @arg2);
    }
}

カリー化させたいサブルーチンと、必要な引数の数を渡す。

sub add2 {
    my ($a,$b) = @_;
    return $a + $b;
}

my $ca = curry(\&add2, 2);
say &$ca(1,2);

my $ca2 = curry(\&add2, 2, 1);
say &$ca2(2);

say "=============";

sub mul3 {
    my ($a,$b,$c) = @_;
    return $a * $b * $c;
}

my $cm = curry(\&mul3, 3);
say &$cm(2,3,4);

my $cm2 = &$cm(2);
say &$cm2(3,4);

my $cm3 = curry(\&mul3, 3, 2, 3);
say &$cm3(4);

my $cm4 = curry(\&mul3, 3, 2);
my $cm5 = &$cm4(3);
say &$cm5(4);

@_のおかげか、書きやすかった。
その分、最初に必要な引数の数を教えてあげる必要があるのが残念だが。

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?