Lau B. Jensen wrote:
> feel...less than idiomatic. I'm hoping a few friendly
> J'ers will be able to spot where Im going wrong
> here.
Ah, now I'm getting ready for the Nutcracker, so I can't reply in too much
detail (ironic!), but in short:
> #1: Find the sum of all multiples of 3 and 5 below 1000
> 3 5 (some func) i.1000
3 5 |/ i. 20
0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1
0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4
3 5 (0 = |/) i. 20
1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0 0 1 0
1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0
3 5 *./@:(0 = |/) i. 20
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
3 5 (0 *./@:= |/) i. 20
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
3 5 (] #~ 0 *./@:= |/) i. 20
0 15
> #2: Sum of all fibs below 4 mill
> Firstly the Fibonacci definition for Learning J throws a curved ball
> near the end:
> fib=: u ^: (v1 `v2)
> ... what is it doing here?
the phrase u^:(v1`v2) y is identical to u^:(v1 y) (v2 y) . But this has
to do more with the definition of ^: [1] than gerunds specifically.
> +/ (#~ <&(4*1e6)) (((0=2&|) # ]) fib 40x)
You might be interested in the Fibonacci sequence essay on our Wiki [2].
> (take while < 4 mill and only the evens)
You could say (#~ <&4e6 *. 0=2&|) fib 40x but it would probably be
rendered in English more like "filter where" instead of "take while". This
is relevant to your next question:
> I couldn't figure out how to just let an infinite amount of
> Fibonacci numbers return
J doesn't have lazy evaluation (yet).
> fibs^:a:
That won't work; the Fibonacci sequence is unbounded (it has no limit to
stop at, no fixed point to home-in on). (Also you'd have to change the ^:
inside fibs, rather than append a new one to the end of it.)
> ((-:|.)@:":)"0 NB. Tests for palindrome
To break this down, right-to-left (as J verbs are read):
"0 NB. For every number individually,
@:": NB. get its decimal string representation
-:|. NB. and tell whether it matches (-:) its own reverse (|.)
However, for the beginning, I suggest you eschew tacit programming and
function composition (@: &: etc). Learn the basics of the language by
typing sentences strings of verbs and nouns in the IJX window, and then
learn to make these reusable (abstracted from the specific nouns) by quoting
them (e.g. 3 : 'sentence' or 4 : 'sentence' ) and replacing the nouns
with our lambda, y (if I understand what a lambda is) as appropriate.
Also, you can have multiline functions with eg:
pali =: verb define
digits =. ":y
digits -: |. digits
)
an a script file, and call them in the IJX window:
(pali"0) 121 222 331 0
1 1 0 1
-Dan
[1] http://www.jsoftware.com/help/dictionary/d202n.htm
[2] http://www.jsoftware.com/jwiki/Essays/Fibonacci%20Sequence
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm