Skip to content

Instantly share code, notes, and snippets.

@kimoto
Created March 8, 2017 09:09
Show Gist options
  • Select an option

  • Save kimoto/55538d1986766cd346e0347dd06a241d to your computer and use it in GitHub Desktop.

Select an option

Save kimoto/55538d1986766cd346e0347dd06a241d to your computer and use it in GitHub Desktop.
perlのsortないで関数呼び出しをすると意図する回数より多く関数呼出しされてしまうかもの件 (n^2)
(Hoge->new(3), Hoge->new(2), Hoge->new(1)) 並び順のデータのソートだと、4回関数が呼ばれる
(Hoge->new(1), Hoge->new(2), Hoge->new(3)) だと、上記例(result.txt)のように6回関数が呼ばれる
なので事前にすべて計算をしておいてその値でソートをするか、いわゆるmemo化のように関数内でキャッシュを作成しておかないとダメかもしれない
#!/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);
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' )
];
@kimoto
Copy link
Copy Markdown
Author

kimoto commented Mar 8, 2017

for kal san

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment