Skip to content
CCPEDIAby Unity Nodes
App Development

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

3 posts207 views1 likesLast activity Aug 2022

  1. 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 : 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

  2. 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.

  3. cohen.avraham

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