2015-09-27 86 views
1

该代码的目的是定义一个sub apply_2nd_deg_polys,它取得一个匿名第二度多项式列表和一个数字列表,并将每个多项式应用于列表中的每个数字。 任何帮助表示赞赏! (:给定三元组生成二次多项式

my @coeffs = ([1,2,3], [4,5,6]); 
my @polys = gen_2nd_deg_polys(@coeffs); 
my @numbers = (1..5); 
my @poly_maps = apply_2nd_deg_polys2(\@polys, \@numbers); 

输出应该是:

[('1x^2 + 2x + 3 at x = 1 is ', 6), ('4x^2 + 5x + 6 at x = 1 is ', 15), ('1x^2 + 2x + 3 at x = 2 is ', 11), ('4x^2 + 5x + 6 at 
x = 2 is ', 32), ('1x^2 + 2x + 3 at x = 3 is ', 18), ('4x^2 + 5x + 6 at x = 3 is ', 57), ('1x^2 + 2x + 3 at x = 4 is ', 27), 
('4x^2 + 5x + 6 at x = 4 is ', 90), ('1x^2 + 2x + 3 at x = 5 is ', 38), ('4x^2 + 5x + 6 at x = 5 is ', 131)] 

这里是我到目前为止的代码...

sub apply_2nd_deg_polys{ 
    my @list = @_; 
    my @polys = @{%_[0]}; my @numbers = @{@_[1]}; 
    push @list, $polys[0][i]; 
    push @list, $polys[i][0]; 
    return @list; 

} 

这里是它我工作的Python变化:

def apply_2nd_deg_polys(polys,numbers): 
    newlist = [] 
    for number in numbers: 
     newlist.append(polys[0](number)) 
     newlist.append(polys[1](number)) 
    return newlist 

回答

1

忽略几乎所有的哟你的问题,Python代码转换成Perl的一个(也许是过度字面的)翻译是:

sub apply_2nd_deg_polys { 
    my ($polys, $numbers) = @_; 
    my $newlist = []; 
    for my $number (@$numbers) { 
     push @$newlist, $polys->[0]->($number); 
     push @$newlist, $polys->[1]->($number); 
    } 
    return $newlist; 
} 
+0

我其实认为这是有效的。不过,我是perl的新手,那么如何将poly_maps(或从此返回的内容)打印到控制台上?我试图打印@poly_maps,我认为它给了我一个内存位置。 –

+1

@TerikBrunson该代码返回对数组的引用。你可以尝试'我的$ ref = apply_2nd_deg_polys(...);打印“@ $ ref \ n”;'但如果任何元素是引用,那也不会很有帮助。尝试'使用Data :: Dumper;打印Dumper($ ref);'看看里面有什么。 – melpomene

+0

是的,这工作。作为一个方面说明,你知道我怎样才能写出同样的东西,但是每个推入的元素用逗号分隔吗?谢谢(: –