[Jprogramming] A q for starters - composing without forking (% +/ %)
bill lam
bbill.lam at gmail.com
Thu Feb 4 11:27:58 HKT 2010
ĵaŭ, 04 Feb 2010, Alex Gian skribis:
> Hi - complete newbie to J here. Though I like what I've seen so far.
>
> Here's my starter question:
> I'd like to code the function that gives the inverse of a sum of
> inverses (eg. like when calculating resistors in parallel)
>
> It works fine if I just write it out as
> % +/ % 10 20 40 (ans 5.71429)
>
> However, if I try to make a function of it,
> invsuminv =. % +/ %
> it becomes a fork (I guess that _does_ make sense), and just computes
> the "cross-sum" of the inverses, as if I'd typed
> (% +/ %) 10 20 40
> 0.2 0.15 0.125
> 0.15 0.1 0.075
> 0.125 0.075 0.05
>
> How can I avoid this? I've tried all sorts of combinations, using @ and
> & but can't seem to crack it. Obviously something fundamental I'm not
> grasping. Any help appreciated.
The reason why @ failed is the rank of % is 0. That means
% 10 20 40
can give result you expected but % itself can only see each atom one
by one, something like this, (do not worry, actual calculation will not
be that inefficient)
(% 10) , (% 20) , (% 40)
now rank of % is inherent by @ so inside the verb
(+/ @ %)
the rank of +/ become rank 0, meaning the summation is not over the
entire array but over individual atom, produce something like
(+/ % 10) , (+/ % 20) , (+/ % 40)
Rank of _verb_ is a fundamental concept in J, and the ranks (note
plural) of every primitive verb is clearly written on the top of page
(for that verb) in the dictionary of J.
also %@:+/@:% does not work because it is interpreted as
(%@:+)/@:% so you have to parenthesis +/
--
regards,
====================================================
GPG key 1024D/4434BAB3 2008-08-24
gpg --keyserver subkeys.pgp.net --recv-keys 4434BAB3
More information about the Programming
mailing list