Perhaps a new closure design inspired by C++ and even Rust is worth 
considering? IMO a good first step would be making Nims' overloadable call 
operator non-experimental? After all, closures are a poor mans' object, right? 
More seriously, I think this design popped up in C++ because it already had the 
overloaded call operator, and the horribly named Functor idiom. a bit of syntax 
sugar and compiler magic gave us C++ lambdas.

@tsojtsoj, if the experimental call operator is OK, then you can use something 
like this
    
    
    {.experimental: "callOperator".}
    
    type State = int
    type Closure = object
        addrOfState: ptr State
    
    
    func hereIsAFunction(state: State, m: int): int =
        result = m mod state
    
    proc `()`(c: Closure, m: int):int = return hereIsAFunction(c.addrOfState[], 
m)
    
    func blabla(d: int, aFunction: Closure): int =
        return aFunction(d)
    
    proc world(state: var State, o, depth: int): int =
        if depth == 0:
            return 200
        
        let c = Closure(addrOfState: addr state)
        result = blabla(d = 0, aFunction = c)
        
        result += state.world(o + depth, depth-1) + state.world(o, depth-1)
    
    var state = 4
    
    echo state.world(0, 26)
    
    
    Run

which I found about 10X faster on my machine than the original slow version you 
wrote. YMMV of course.

I don't like having to use pragmas like {.nimcall.} and {.closure.}. 

Reply via email to