What do we call this (new?) higher-order function?

后端 未结 16 1690
盖世英雄少女心
盖世英雄少女心 2021-02-05 23:44

I am trying to name what I think is a new idea for a higher-order function. To the important part, here is the code in Python and Haskell to demonstrate the concept, which will

16条回答
  •  长情又很酷
    2021-02-06 00:36

    Nice idiom! I just needed to use this in Perl to determine the time between sequential events. Here's what I ended up with.

    sub pinch(&@) {
      my ( $f, @list ) = @_;
      no strict "refs";
    
      use vars qw( $a $b );
    
      my $caller = caller;
      local( *{$caller . "::a"} ) = \my $a;
      local( *{$caller . "::b"} ) = \my $b;
    
      my @res;
      for ( my $i = 0; $i < @list - 1; ++$i ) {
        $a = $list[$i];
        $b = $list[$i + 1];
        push( @res, $f->() );
      }
      wantarray ? @res : \@res;
    }
    
    print join( ",", pinch { $b - $a } qw( 1 2 3 4 5 6 7 ) ), $/;
    # ==> 1,1,1,1,1,1
    

    The implementation could probably be prettier if I'd made it dependent on List::Util, but... meh!

提交回复
热议问题