# Considering:
    
    
    # Any suggestions on handling common problem destructuring of
    # array/seq into a list of named fields?
    # (This is quite common when parsing CSV's and the like)
    
    import strutils
    
    var first, last, phone: string  # usually many more fields
    
    # Given an input source with an array or seq of fields:
    var fieldList = ["John", "Smith", "1-416-999-1234"] # usually from an 
external source
    
    # Is there an more concise way to destructure the list into named fields?
    (first, last, phone) = (fieldList[0], fieldList[1], fieldList[2])
    # which gets tedious as the number of fields increases especially if there 
is
    # the potential for optional trailing fields.
    
    echo [first, last, phone].join ", "
    
    # Ideally something like
    #   (first, last, phone ...) = (fieldList)
    # would be nice but obviously conflicts with tuple assignment semantics.
    
    # I suppose I could define object type with a constructor taking an 
openArray:
    
    type Person = object
      first, last, phone: string # Again... Usually many more fields
    
    proc initPerson(fieldList: openArray[string]): Person =
      result = Person()
      if fieldList.len > 0 : result.first = fieldList[0]
      if fieldList.len > 1 : result.last  = fieldList[1]
      if fieldList.len > 2 : result.phone = fieldList[2]
      # ...
    
    echo initPerson ["John", "Smith", "1-416-999-1234"]
    echo initPerson ["Mary ", "Brown"]
    
    # But it would be nice to avoid the type and constructor boilerplate for 
trivial cases.
    # Probably there some macro exists which handles such simple destructering.
    # Any suggestions/pointers would be appreciated.
    
    
    
    Run

Reply via email to