1. I'm not an expert in nim-decimal, but apparently it's the default way. But 
you can always make a 'round' procedure (by wrapping 'quantize') if you're more 
comfortable with it.
  2. It can't be pure because +, - , etc.. operators defined by nim-decimal 
rely on global decimal context (`Hint: '+' accesses global state 'CTX_ADDR'`). 
For procedure to be pure - all procedures inside of it should also be pure.
  3. you can create your custom types which would work as an alias for other 
types, and you can use a single type with multiple procedure arguments to 
reduce typing:


    
    
    type Dec = DecimalType
    proc wacc(e, d, rE, rD, t: Dec ): Dec  =
    
    
    Run

3.5 you can use a single let, var, const, type.. instead of multiple:
    
    
    let
      a = 1
      b = 2
    
    
    Run

  4. brilliantly answered by ElegantBeef



If we combine all of techniques, we will get very idiomatic Nim code:
    
    
    type Dec = DecimalType
    
    template `'dec`(s: string | SomeInteger): DecimalType = newDecimal(s)
    
    proc wacc(e, d, rE, rD, t: Dec ): Dec  =
      let
        v = e + d
        eV = e / v
        dV = d / v
        adjRD = rD * (1 - t)
      
      eV * rE + dV * adjRD
    
    let
      e = 1000000'dec
      d = 2000000'dec
      rE = 0.15'dec
      rD = 0.05'dec
      t = 0.3'dec
    
    let w = wacc(e, d, rE, rD, t)
    let y = quantize(w, newDecimal("1e-3"))
    echo reduce(y * 100), '%'
    
    
    Run

Reply via email to