scala – Perl 6中的模式匹配是否有保护条款?
在
scala中,模式匹配具有保护模式:
val ch = 23 val sign = ch match { case _: Int if 10 < ch => 65 case '+' => 1 case '-' => -1 case _ => 0 } Perl 6版本是这样的吗? my $ch = 23; given $ch { when Int and * > 10 { say 65} when '+' { say 1 } when '-' { say -1 } default { say 0 } } 这是正确的吗? 更新:正如jjmerelo建议的那样,我发布我的结果如下,签名版本也很有趣. multi washing_machine(Int x where * > 10 ) { 65 } multi washing_machine(Str x where '+' ) { 1 } multi washing_machine(Str x where '-' ) { -1 } multi washing_machine(x) { 0 } say washing_machine(12); # 65 say washing_machine(-12); # 0 say washing_machine('+'); # 1 say washing_machine('-'); # -1 say washing_machine('12'); # 0 say washing_machine('洗衣机'); # 0 解决方法
我写了两个答案.这个回答标题中的问题. (另一个回答你帖子正文中的“这是对的吗?”问题.)
“Perl 6中的模式匹配是否具有保护条款?” 根据我对Scala的了解,一些/大多数Scala模式匹配实际上对应于使用Perl 6签名. (在这种情况下,保护条款通常是 从The Point of Pattern Matching in Scala开始引用Scala的创建者Martin Odersky:
Perl 6 signatures涵盖了几个用例(yay,puns).这些包括Perl 6等效的函数式编程范式用法,其中一个匹配值’或函数’类型签名(参见Haskell)和面向对象编程范例用法,其中一个匹配嵌套数据/对象并拉出所需位(cf斯卡拉). 考虑一下这个Perl 6代码: class body { has ( $.head,@.arms,@.legs ) } # Declare a class (object structure). class person { has ( $.mom,$.body,$.age ) } # And another that includes first. multi person's-age-and-legs # Declare a function that matches ... ( person # ... a person ... ( :$age where * > 40,# ... whose age is over 40 ... :$body ( :@legs,*% ),# ... noting their body's legs ... *% ) ) # ... and ignoring other attributes. { say "$age {+@legs}" } # Display age and number of legs. my $age = 42; # Let's demo handy :$var syntax below. person's-age-and-legs # Call function declared above ... person # ... passing a person. .new: # Explicitly construct ... :$age,# ... a middle aged ... body => body.new: :head,:2arms,legs => <left middle right> # ... three legged person. # Displays "42 3" 请注意,上面有一个与Scala模式匹配的保护条款相当的近似值 – 其中*> 40.(这可以很好地捆绑到 我们可以定义对应不同情况的其他multis,如果他们的妈妈的名字与特定的正则表达式或其他任何东西匹配,可能会拉出人的腿的“名字”(“左”,“中间”等) – 你希望得到图片. 一个不打扰解构该人的默认情况(多个)可能是: multi person's-age-and-legs (|otherwise) { say "let's not deconstruct this person" } (在上面我们已经使用|到slurp up all remaining structure/arguments passed to a multi在签名中添加了一个参数.鉴于我们对那些混乱的结构/数据没有任何作用,我们可以只写(|).) 不幸的是,我认为官方文档中没有提到签名解构.有人可以写一本关于Perl 6签名的书. (字面意思.当然,这是一种很好的方式 – 唯一的方式,甚至 – 写东西.我最喜欢的文章解析了Perl 6签名的一些功能,从2013年开始是Moritz的Pattern Matching and Unpacking.谁撰写了Perl 6书籍这是希望.) Scala的匹配/案例和Perl 6的给定/似乎更简单 确实. 正如@jjmerelo在评论中指出的那样,使用签名意味着对于每个案例都有一个多foo(…){…},这在句法上比案例更重…… => …. 缓解: >更简单的案例可以使用给定/何时,就像你在问题正文中所写;> Perl 6可能有一天会得到非实验性的宏,可以用来实现一个看起来更接近Scala的匹配/案例结构的构造,从而避免重复的多个foo(…)s. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |