DA.Traversable | Examples

Hi Everyone,

Can anyone provide some code examples for DA.Traversable for better understanding.

Thank you!

Hi,

DA.Traversable defines a typeclass for “structures that can be traversed from left to right, performing an action on each element”.

A typical action that you might want to perform is to fetch or create a contract on the ledger. So, for instance, given a template T you could define

myAction : ContractId T -> Update T
myAction = fetch

You can then use the fact that a list is Traversable to fetch all contract ids stored in a list (using mapA defined in the Prelude):

fetchAllContractIds : [ContractId T] -> Update [T]
fetchAllContractIds cids = mapA myAction cids

You could also use the fact that an Optional is Traversable to implement a function that fetches a contract when the option is not None:

fetchContractIfSome : Optional (ContractId T) -> Update (Optional T)
fetchContractIfSome cidO = mapA myAction cidO

In this last case, you would need to use the generic mapA defined in DA.Traversable to perform the action.

Finally, if you are working with custom data structures, you could define your own Traversable instances.

Here is an example which I wrote some time ago, when I was trying to get a grasp on traversables: Example own Traversable · GitHub

I hope this helps!

1 Like