Is “map” a loop?

后端 未结 15 1818
自闭症患者
自闭症患者 2020-12-14 14:29

While answering this question, I came to realize that I was not sure whether Perl\'s map can be considered a loop or not?

On one hand, it quacks/walks l

相关标签:
15条回答
  • 2020-12-14 15:19

    No, it is not a loop, from my perspective.

    Characteristic of (perl) loops is that they can be broken out of (last) or resumed (next, redo). map cannot:

    map { last } qw(stack overflow);  # ERROR!  Can't "last" outside a loop block
    

    The error message suggests that perl itself doesn't consider the evaluated block a loop block.

    0 讨论(0)
  • 2020-12-14 15:22

    A map in Perl is a higher order function that applies a given function to all elements of an array and returns the modified array.

    Whether this is implemented using an iterative loop or by recursion or any other way is not relevant and unspecified.

    So a map is not a loop, though it may be implemented using a loop.

    0 讨论(0)
  • 2020-12-14 15:25

    Map only looks like a loop if you ignore the lvalue. You can't do this with a for loop:

    print join ' ', map { $_ * $_ } (1 .. 5)
    1 4 9 16 25
    
    0 讨论(0)
提交回复
热议问题