daml - 如何在 DAML 的列表中找到特定元素的索引?
问题描述
假设我有一个如下所示的列表:
let identifiers = ["ABC123", "DEF456", "GHI789"]
我想知道元素“DEF456”的索引。完成此任务的推荐方法是什么?
解决方案
findIndex
标准库中模块中的Base.List
函数,做你想做的事。
daml 1.0 module FindIndex where
import Base.List
import Base.Maybe
test foo : Scenario {} = scenario
let
identifiers = ["ABC123", "DEF456", "GHI789"]
index: Maybe Integer = findIndex ((==) "DEF456") identifiers
assert $ index == Just 1
在 DAML 中的大多数列表操作,包括findIndex
使用foldr
和实现foldl
。
-- Returns the index of the first element in the list satisfying the predicate, or M.Nothing if there is no such element.
def findIndex (f: a -> Bool) (xs: List a) : Maybe Integer =
headMay (findIndices f xs)
-- Returns the indices of all elements satisfying the predicate, in ascending order.
def findIndices (f: a -> Bool) (xs: List a) =
let work acc x =
let i = fst acc
let is = snd acc
tuple (i + 1) (if f x then cons i is else is)
reverse (snd (foldl work (tuple 0 nil) xs))
推荐阅读
- angular - 以下所有目录的角度隐藏标题
- python - 如何检查一个数组是否在python的数组列表中?
- python - python中的pandas操作放慢速度
- python - python - 如何将带有列表的字典转换为python中每个关联键的值不相等的字典列表?
- java - Spring Boot 控制器测试加载整个应用程序上下文
- python - Python - 检查是否存在所有列名数据框
- powershell - 使用 API powershell 将 ITGlue 联系人分配给字段
- r - 如何更改 roxygen 文档中超链接的颜色?
- python - Python(PyTorch):TypeError:字符串索引必须是整数
- kubernetes - ActiveMQ Artemis 在通配符队列更改目标上重新分配消息