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

后端 未结 16 1570
盖世英雄少女心
盖世英雄少女心 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:30

    In Python the meld equivalent is in the itertools receipes and called pairwise.

    from itertools import starmap, izp, tee
    
    def pairwise(iterable):
        "s -> (s0,s1), (s1,s2), (s2, s3), ..."
        a, b = tee(iterable)
        next(b, None)
        return izip(a, b)
    

    So I would call it:

    def pairwith(func, seq):
        return starmap(func, pairwise(seq))
    

    I think this makes sense because when you call it with the identity function, it simply returns pairs.

    0 讨论(0)
  • 2021-02-06 00:35

    So because there seems to be no name for this I suggest 'merger' or simple 'merge' because you are merging adjacent values together.

    So merge is already taken so I now suggest 'meld' (or 'merger' still but that may be too close to 'merge')

    For example:

    meld :: (a -> a -> b) -> [a] -> [b]
    meld _ [] = []
    meld f xs = zipWith f (init xs) (tail xs)
    

    Which can be used as:

    > meld (+) [1..10]
    [3,5,7,9,11,13,15,17,19]
    > meld compare "hello world"
    [GT,LT,EQ,LT,GT,LT,GT,LT,GT,GT]
    

    Where the second example makes no real sense but makes a cool example.

    0 讨论(0)
  • 2021-02-06 00:36

    this seems like ruby's each_cons

    ruby-1.9.2-p0 > (1..10).each_cons(2).to_a
    
    => [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 8], [8, 9], [9, 10]] 
    
    0 讨论(0)
  • 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!

    0 讨论(0)
提交回复
热议问题