Created
March 8, 2017 09:09
-
-
Save kimoto/55538d1986766cd346e0347dd06a241d to your computer and use it in GitHub Desktop.
perlのsortないで関数呼び出しをすると意図する回数より多く関数呼出しされてしまうかもの件 (n^2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(Hoge->new(3), Hoge->new(2), Hoge->new(1)) 並び順のデータのソートだと、4回関数が呼ばれる | |
(Hoge->new(1), Hoge->new(2), Hoge->new(3)) だと、上記例(result.txt)のように6回関数が呼ばれる | |
なので事前にすべて計算をしておいてその値でソートをするか、いわゆるmemo化のように関数内でキャッシュを作成しておかないとダメかもしれない |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env perl | |
package Hoge; | |
use strict; | |
use warnings; | |
use Data::Dumper; | |
sub new { | |
my ($class, $value) = @_; | |
return bless(+{ | |
value => $value, | |
}, $class); | |
}; | |
sub get_engagement_score { | |
my ($self) = @_; | |
warn "called get_engagement_score()"; | |
return $self->{value}; | |
}; | |
package main; | |
my @items = (Hoge->new(3), Hoge->new(2), Hoge->new(1)); | |
my @sorted = sort { $a->get_engagement_score <=> $b->get_engagement_score } @items; | |
use Data::Dumper; | |
warn Dumper(\@sorted); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
perl hoge.pl | |
called get_engagement_score() at hoge.pl line 16. | |
called get_engagement_score() at hoge.pl line 16. | |
called get_engagement_score() at hoge.pl line 16. | |
called get_engagement_score() at hoge.pl line 16. | |
called get_engagement_score() at hoge.pl line 16. | |
called get_engagement_score() at hoge.pl line 16. | |
$VAR1 = [ | |
bless( { | |
'value' => 1 | |
}, 'Hoge' ), | |
bless( { | |
'value' => 2 | |
}, 'Hoge' ), | |
bless( { | |
'value' => 3 | |
}, 'Hoge' ) | |
]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
for kal san