Find an item from a list that matches a certain criteria
- ronihOP
In case of a type definition and a variable declaration from that type:
data Relation = Relation with
var1: Text
var2: Text
var3: Textrelations: 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
- Julius_William 1
You can use
filterto 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-41317Type 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 - ronih
@Julius_William Thanks a lot
- cocreature 1
If you’re only interested in the first match, you might also want to consider find.
- ronih
@cocreature Thanks. I’ll try it
