【问题标题】:How do I find the index of a particular element within a List in DAML?如何在 DAML 的列表中找到特定元素的索引?
【发布时间】:2019-01-22 17:09:33
【问题描述】:

假设我有一个如下所示的列表:

let identifiers = ["ABC123", "DEF456", "GHI789"]

我想知道元素“DEF456”的索引。完成此任务的推荐方法是什么?

【问题讨论】:

    标签: daml


    【解决方案1】:

    daml 1.2 中,您可以像这样使用DA.List 标准库模块中的elemIndex : Eq a => a -> [a] -> Optional Int 函数:

    daml 1.2 module MyModule where
    
    import DA.List
    
    indexOfElement = scenario do
      let identifiers = ["ABC123", "DEF456", "GHI789"]
          index : Optional Int = elemIndex "DEF456" identifiers
      assert $ index == Some 1
      return index
    

    【讨论】:

      【解决方案2】:

      标准库中Base.List 模块中的findIndex 函数可以满足您的需求。

      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)实际上是使用 foldrfoldl 实现的。

      -- 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))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-16
        • 2021-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-28
        • 1970-01-01
        相关资源
        最近更新 更多