Like sortIt() or applyIt() where we are forced to use the it variable name in 
the condition?

When I started with Nim some years ago I thought that that is the only possible 
way to do it in Nim -- but I always regard it as very ugly.

I just remembered that I tried successfully to use a custom variable name some 
time ago. I think it was something like this:
    
    
    #The original Nim version:
    template applyIt*(varSeq, op: untyped) =
      for i in 0 .. <varSeq.len:
        let it {.inject.} = varSeq[i]
        varSeq[i] = op
    
    var nums = @[1, 2, 3, 4]
    nums.applyIt(it * 3)
    assert nums[0] + nums[3] == 15
    
    # the new version with custom name
    template apply*(varSeq, el, op: untyped) =
      for el in mitems(varSeq):
        el = op
    
    nums = @[1, 2, 3, 4]
    nums.apply(el, el * 3)
    assert nums[0] + nums[3] == 15
    echo nums
    

Personally I regard the call nums.apply(el, el * 3) as much nicer. It looks 
more like the Ruby code, where we have for example
    
    
    a = [ "a", "b", "c" ]
    a.delete_if {|x| x >= "b" }   #=> ["a"]
    

I have not yet investigated if other It templates like sortIt() can be 
rewritten in this way too, but I hope so. 

Reply via email to