Find an item from a list that matches a certain criteria

In case of a type definition and a variable declaration from that type:

data Relation = Relation with
var1: Text
var2: Text
var3: Text

relations: Relation

Now, let’s say I want to create a list of that type - meaning [relations]:
How can i filter the list and find the item that matches a certain criteria
(e.g relations.var2 == “xyz”)

Thanks

You can use filter to only include all items that match a certain criteria using the prelude filter function, assigning it to a new list variable.
https://docs.daml.com/daml/stdlib/Prelude.html#function-da-internal-prelude-filter-41317

Type declaration is necessary to prevent ambiguous type reference error in the filter function.
Also keep in mind that you have to add “deriving (Eq,Show)” in your data type to enable pattern matching for the data type.

In this case,
let filteredList= filter (\(var : Relation) -> var.var2=="xyz") listVariable

1 Like

@Julius_William Thanks a lot

If you’re only interested in the first match, you might also want to consider find.

1 Like

@cocreature Thanks. I’ll try it :slight_smile: