Hello, everyone.
Recently, there was a question on passing more than two arguments to a
verb on this mailing list and my response was:
first=. 0{]
second=. 1{]
third=. 2{]
f=. first + second * third
f 1 2 3
7
Of course, there is a way of passing a list of arguments and
separately assign them into different names using multiple
assignments:
f=: 3 : 0
'a b c' =. y
a+b*c
)
f 10 2 3
16
f 10;2;3
16
At the time, I thought that this sort of passing more than two
arguments should be a last resort. There might be a better way of
reorganizing the verbs and arguments so that passing more than two
arguments isn't needed in the first place. Looking at the problem from
a new perspective(usually, J-friendly one) helps. You should come up
with a whole new model of solving the problem.
I think that's why Miller, Raul D answered as:
[quote]
It's really not a good idea to focus too narrowly on a specific part
of a calculation -- it's better to start with an overall description
of the problem at hand.
A couple other examples
NB. scale and add
([: +/ 2 3 4 * ]) list
42
NB. polynomial
list p. 100
100001
[/quote]
This is a very good advice, and I wholeheartedly agree.
Now I'm thinking of a different approach. Still maintaing the same
model of solving the problem, you could avoid passing around more than
two arguments. I'll use interest calculation for the example. Have a
look at "http://en.wikipedia.org/wiki/Interest" for the formulae, in
case you aren't sure of it.
at=:*
percent=: adverb def '0.01*m'
year=:years=: adverb def 'm'
NB. what we want is....
NB. $4500 at 9.5 percent simple interest for 6 years
NB. and almost a direct translation is possible
NB. (you could choose your, or your customer's preferable level of verbosity)
simplefor=:1+*
(4500*(1+0.095*6))-: 4500 at 9.5 percent simplefor 6 years
1
compoundfor=:>:@[^]
(4500*(1+0.095)^6)-: 4500 at 9.5 percent compoundfor 6 years
1
Now we want to extend the verb compoundfor to treat multiple times of
payment in a year:
NB. times per year
tpy=:conjunction : (':';' (x%u) v (y*u) ')
(2000*(1+0.095%3)^3*5)-: 2000 at 9.5 percent 3 tpy compoundfor 5 years
1
In the wiki page, it says "Many banks advertise an annual percentage
yield (APY) which is the return on the principal over an entire year.
For example, a 5% rate compounded monthly would have an approximate
APY of 5.12%." Incidentally, we can easily calculate APY thanks to the
decomposition of the calculation:
NB. annual percentage yield
0.005 >: | 5.12 percent - <: 5 percent 12 tpy compoundfor 1 year
1
We could even abstract it away with a new verb, say apy, for example:
apy=: 13 : '<: x y tpy compoundfor 1 year'
5 percent apy 12
0.0511619
Any comments and suggestions?
June
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm