How to set a specific element inside a list which is part of another data type
- cohen.avrahamOP
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 : TypeListI am trying to set the
valueIntfield of the first instance oftypeSinglelist when creating an instance ofTypeExample.I am familiar with the
headfunction, 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 = someValueThanks
- cocreature 1
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.
- cohen.avraham
Thank you @cocreature for your answer. I wish there was something I could do in one statement.