Search code examples
callprocedureprocnim-lang

How to call function in Nim based on a number without ifs?


So I want to write a procedure to which I'll pass a number and it will call some other function based on the number I gave it. It could work something like this:

#example procs

proc a(): proc =
  echo 'a'
proc b(): proc =
  echo 'b'

proc callProcedure(x:int): proc =
  if x>5:
    a()
  else:
    b()

callProcedure(10)  #calls function a
callProcedure(1)   #calls function b

However I want to do this without ifs. For example I was looking into somehow storing a reference to the functions in an array and call it via its index but I could not get that to work and I've got the suspicion it cannot be done (in which case I would like to understand why). I am also interested in other ways of achieving the same result. I've got multiple reasons why I want to do this: a) I've read ifs are slow(er-ish) among other things (like that novices should leave optimizing them up to the compiler so I know I don't have to even think about it but I would like to try something like this to learn nonetheless) b) I think it opens up some possibilities like being very dynamic in the order of and which procedures will be called c) just out of curiosity

Some of the things I've looked at in relation to this but could not manage to find/learn what I need from them:

Nim return custom tuple containing proc

Nim stored procedure reference in tuple

PS: I'm very new to this so if I missed something obvious feel free to point me in the right direction.

Thanks in advance!


Solution

  • You can store procedures in an array just fine, but they have to be of the same type:

    proc a() =
      echo "a"
    
    proc b() =
      echo "b"
    
    let procs = [a, b]
    
    proc callProcedure(x: int) =
      procs[int(x <= 5)]()
    
    callProcedure(10)  # Calls function a
    callProcedure(1)   # Calls function b
    

    You don't need the "proc" return type. Also this still uses comparisons under the hood for x <= 5, so there's that. And ifs aren't slow.