## I would appreciate a Nim implementation of Ruby's **tap()** method.

This is one of those _little helper_ functions I miss from my old Ruby days,

where **tap()** :

Yields self to the block, and then returns self.

The primary purpose of this [method](https://apidock.com/ruby/Object/method) is 
to “[tap](https://apidock.com/ruby/Object/tap) into” a 
[method](https://apidock.com/ruby/Object/method) chain, in order to perform 
operations on intermediate results within the chain.

### Example:
    
    
    puts "Result = ", 123.tap{|i| puts "Double = ", 2*i}
    Double = 246
    Result = 123
    
    
    Run

### Bing suggested code:
    
    
    proc tap[T](obj: T, block: proc (obj: var T)) =
      block(obj)
      result = obj
    
    
    Run

Not surprisingly the above fails to compile :-)

After a little massaging, I can get it compile but the sample invocation (i.e 
last line) doesn't :-(
    
    
    proc tap*[T](obj: T, code: proc(obj: var T)): T =
      code obj
      obj
    
    let code = proc(i: var int): int {.closure.} =
      echo 2*i
      result = 321
    
    var num = 123
    echo num.tap(code)
    
    
    Run

The compiler tells me:
    
    
    temp.nim(10, 9) Error: type mismatch
    Expression: tap(num, code)
      [1] num: int
      [2] code: proc (i: var int): int{.closure, gcsafe.}
    
    Expected one of (first mismatch at [position]):
    [2] proc tap[T](obj: T; code: proc (obj: var T)): T
      expression 'code' is of type: proc (i: var int): int{.closure, gcsafe.}
    
    
    Run

**As usual, any suggestions would be appreciated**

Reply via email to