问题描述
来自文档
但是然后:
my $list = [[1,2,3],[[4,5],6,7]];
say $list.deepmap( *² ); # [[1 4 9] [[16 25] 36 49]]
say $list.duckmap( *² ); # [9 9]
deepmap 的行为与预期的差不多,但是我真的无法理解duckmap
在做什么.
deepmap behaves pretty much as expected, but I can't really make any sense of what duckmap
is doing.
此问题与此问题在perl6/doc 中有关.可以用它们之间没有更多不同"来解决,但是我想找到一些示例,说明它们在哪里做同样的事情,而在不这样做的情况下,请尝试真正了解正在发生的事情.
This question is related to this issue in perl6/doc. It can be solved with "They couldn't be more different", but I would like to find some examples where they do the same, and when they don't, try and understand really what's going on.
推荐答案
duckmap
中的 duck 是 duck-typing ;那就是如果它走路像鸭子,说话像鸭子,那一定是鸭子."
The duck in duckmap
refers to duck-typing; that is "if it walks like a duck and talks like a duck, it must be a duck."
> say [1,2.2,"3.4",4,"a"].duckmap(-> Str $_ { use fatal; .Int }).perl
[1, 2.2, 3, 4, "a"]
(use fatal
在那里,因此"a".Int
失败对象成为引发的异常,因此duckmap
会捕获该异常并返回原始数据)
(use fatal
is there so that the "a".Int
failure object becomes a thrown exception, so that duckmap
catches it and returns the original data instead)
这对于更改输入的一小部分很有用,而不必专门处理所有可能的输入.
This is useful for changing small portions of the input without having to specially deal with every possible input.
> say [1,2.2,"3.4",4,"a"].map(-> $_ { $_ ~~ Str ?? .Int // .self !! .self }).perl
[1, 2.2, 3, 4, "a"]
> say [1,2.2,"3.4",4,"a"].deepmap(-> $_ { $_ ~~ Str ?? .Int // .self !! .self }).perl
[1, 2.2, 3, 4, "a"]
duckmap
与其他map
之间的差异更大,但它们都是存在这个基本前提的.
There are more differences between duckmap
and the other map
s, but they all are there for this basic premise.
> [ [<a b c>], [1,2,3], [[4,5,6],] ].duckmap(-> @_ where .all ~~ Int { @_.Str } ).perl
[["a", "b", "c"], "1 2 3", ["4 5 6"]]
> [ [<a b c>], [1,2,3], [[4,5,6],] ].map(-> @_ { @_.all ~~ Int ?? @_.Str !! @_.self } ).Array.perl
[["a", "b", "c"], "1 2 3", [[4, 5, 6],]] # doesn't match, as map is one level deep
(请注意,由于deepmap
太深,您无法完全执行上述操作)
为了从map
中获得相同的行为,可能需要做更多的工作.
(Note that you can't do the above at all with deepmap
, as it goes too deep)
In order to get the same behaviour out of map
, would require potentially much more work.
这篇关于duckmap真正做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!