You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在Raku语言的map块中使用数组索引?

Raku中在map例程里获取数组索引的方法

当然可以,Raku提供了几种简洁的方式实现这个需求,以下是常用方法:

  • 使用.kv方法
    .kv会返回数组的索引与对应元素的键值对序列,你可以在map中按顺序捕获索引和元素:

    raku -e 'my @a = "First", "Second", "Third", "First"; say @a.kv.map({ "Index of $^value is: $^key;" })'
    

    这里$^key会捕获索引,$^value捕获元素值,执行后就能得到你想要的输出。你也可以用显式的解构写法让逻辑更清晰:

    raku -e 'my @a = "First", "Second", "Third", "First"; say @a.kv.map(-> ($index, $item) { "Index of $item is: $index;" })'
    
  • 使用.pairs方法
    .pairs返回包含Pair对象的序列,每个Pair的.key属性对应索引,.value属性对应元素:

    raku -e 'my @a = "First", "Second", "Third", "First"; say @a.pairs.map({ "Index of $_.value is: $_.key;" })'
    

两种方法执行后都会输出:

(Index of First is: 0; Index of Second is: 1; Index of Third is: 2; Index of First is: 3;)

内容的提问来源于stack exchange,提问作者Mimosinnet

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 14:37:36