Как мне найти индекс определенного элемента в списке в DAML? - PullRequest
0 голосов
/ 22 января 2019

Скажем, у меня есть список, который выглядит следующим образом:

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

Я хочу знать индекс, если элемент "DEF456".Каков рекомендуемый способ сделать это?

Ответы [ 2 ]

0 голосов
/ 29 января 2019

В daml 1.2 вы можете использовать функцию elemIndex : Eq a => a -> [a] -> Optional Int в стандартном библиотечном модуле DA.List, например:

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
0 голосов
/ 23 января 2019

Функция 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))
...