質問

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.@]

役に立ちましたか?

解決

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

他のヒント

When I want a tacit function I often let 13 : bang it out for me. In this case, some variations:

   13 : '+/ %((1+0.03)^1+i.y)'
[: +/ [: % 1.03 ^ 1 + i.

   13 : '+/ %((1+0.03)^>:i.y)'
[: +/ [: % 1.03 ^ [: >: i.

And with 1+0.03 or whatever as a leftargument:

   13 : '+/ %(x^1+i.y)'
[: +/ [: % [ ^ 1 + [: i. ]

   13 : '+/ %(x^>:i.y)'
[: +/ [: % [ ^ [: >: [: i. ]

There are way too many caps ([:) to call it less ugly, though, but that's a start.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top