How to set a specific element inside a list which is part of another data type

G-d willing

Hello,
Considering I have the following data structures:

data TypeSingle = TypeSingle with
  valueInt : Int

data TypeList = TypeList with
  typeSingle : [TypeSingle]

data TypeExample = TypeExample with 
  typeList : TypeList

I am trying to set the valueInt field of the first instance of typeSingle list when creating an instance of TypeExample.

I am familiar with the head function, however, I am trying to get a way of doing it in one command.

This is how the function should be:

funcExample : TypeExample -> Int -> TypeExample
funcExample sourceExample someValue = 
  sourceExample with
    -- typeList[0].valueInt = someValue

Thanks

There isn’t anything builtin for setting elements at specific indices in a list. You have to pattern match on the list, e.g.,

case typeList of
  x :: xs -> (x.valueInt = someValue) :: xs
  [] -> error "empty list"

Keep in mind that Daml lists are single-linked lists so accessing anything other than the first element can be fairly expensive since you do a linear traversal over the list. You may want to consider using a map instead if you want to modify elements at arbitrary indices.

1 Like

Thank you @cocreature for your answer. I wish there was something I could do in one statement.