duckmap真正做什么? [英] What does duckmap really do?

查看:102
本文介绍了duckmap真正做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自文档

duckmap将在每个元素上应用&block,并返回具有该块的已定义返回值的新列表.对于未定义的返回值,如果duckmap元素实现了Iterable,它将尝试进入该元素.

duckmap will apply &block on each element and return a new list with defined return values of the block. For undefined return values, duckmap will try to descend into the element if that element implements Iterable.

但是然后:

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 maps, 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真正做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆