Not entirely sure what exactly you want findInObjSeq to do. Is this supposed to 
return you a count? An Index? An instance from the list?

Either way, if you want to get past this entirely without macros you will need 
to make use of the `when` keyword instead of "if". And also the fieldpairs 
iterator.

When is like an if-check at compiletime, if you pass the code within the 
when-block gets compiled into the binary, if not it gets excluded.
    
    
    proc findInObjSeq*[T, S](objects: openArray[T], fieldName: static string, 
value: S): int =
      ## Returns index of first occurrence of an object in `objects` that has a 
field named `fieldName` with the value `value`.
      ## Returns -1 if no object in objects has a field named `fieldName`.
      ## Returns also -1 if the objects in `objects` contain a field with that 
name, but no value equaling `value`
      for index, obj in objects:
        for objFieldName, fieldValue in obj.fieldPairs:
          when objFieldName == fieldName:
            if fieldValue == value:
              return index
      
      return -1
    
    
    Run

What this does is:

  1. Iterate at runtime over the various objects in whatever iterable type you 
have in `objects`
  2. Iterate at compileTime over the various fields in an object (it is at 
compileTime because .fieldPairs works that way) and do whatever operation 
inside the loop per field on `T`
  3. For each field you check at compiletime whether its name equals the name 
you defined at the start (so e.g. "food"). If that field has that name, then 
you want to perform the code within the when-block
  4. In the when-block check at run-time whether the value in that `obj` 
instance is equal to `value`. If it is, return thee index of that instance. If 
it isn't, move on.


Reply via email to