Search code examples
jtacit-programming

what is a good tacit form of sum(1/(1+x)^y) in J


As a beginner exercise I tried to calculate the following sum in J, sum(1/(1+0.03)^n for n = 1 to 30 using +/%(1 + 0.03)^ >:i.30. How can I write this into a simple tacit form? all I tried are significantly uglier than the explicit form above like >:@[ (+/&:%)@:^ >:&i.@]


Solution

  • You could start with

    +/@:%@((1 + 0.03) ^ >:@i.) 30
    

    You can make the 0.03 a left argument using a fork, but using a hook can be cleaner

    (1 + 0.03) +/@:%@([ ^ >:@i.@]) 30   NB. use fork
    (1 + 0.03) +/@:%@(^ >:@i.) 30       NB. use hook
    

    The same operation (increment) is being performed on both the left and right arguments to ^. That is a hint that & (Compose) may be useful.

    0.03 +/@:%@(^&>: i.) 30         NB. apply increment to both left & right arg