Extracting list of parties from a list of custom objects

Hi,
I have defined a custom object:

data CustomObj = CustomObj
  with
    name : Party
    age : Int
    deriving(Eq, Show)

And my contract template is:

template MyContract
  with
     owner : Party
     customObjList : [CustomObj]
  where
     signatory owner
     observer //here I need a list of CustomObj.name

I want to extract the name field from each object of the customObjList. Make a list of these names and use it as the list of observers. How can I achieve that.
Thanks.

1 Like

try observer fmap (.name) customObjList

Here you can find more information: https://docs.daml.com/daml/stdlib/Prelude.html#function-ghc-base-fmap-41707

3 Likes

Just to elaborate a bit more, fmap is a function that takes two arguments. The second argument is your list; the first is a function to be applied to every element in that list. (.name) is short for \elem -> elem.name, where the backslash is notation for a function literal aka lambda function.

I suggest you have a peek at our documentation. There is even a new section on functional programming. We also have an online learning platform if that’s more your style.

And welcome to the community!

1 Like

That does the job. Thanks.

As a small side-note: When working with lists, it aids both readability and performance to use plain versions of functions and operators rather than the fancier ones form typeclasses. In this instance using map rather than fmap would make it more obvious that we are dealing with a list, for example.

2 Likes

Thanks @bernhard.