首页 > 解决方案 > 如何在 DAML 中按索引访问列表中的元素?

问题描述

假设一个列表的长度为三,我想访问第二个或中间元素。做这个的最好方式是什么?

标签: daml

解决方案


您可以为此使用列表索引运算符!!,其定义如下:

(!!)
    : [a] -> Int -> a

List index (subscript) operator, starting from 0.

这是一个演示其用法的片段:

first : [Int] -> Int
first x =
  let f = x!!0
  in f

testFirst = scenario do
  assert(first [3, 2, 1] == 3)

推荐阅读