On 25 Mar 2006 at 22:20, Nicholas Spies said:
> To conceal some of the visual noise implicit in J, I (foolishly, no
> doubt) tried to do the following:
>
> NB. define an array in which to store data
> a =: 0 0 0 0 0 0 0 0
>
> NB. simple enough
> get =: 4 : 'x.{ y.'
>
> set =: 4 : '({. x.) (({: x.)}) y.'
>
> ]a =: 3 0 set a
> 3 0 0 0 0 0 0 0
>
> ]a =: 2 0 set a
> 2 0 0 0 0 0 0 0
>
> NB. defining this was the whole point of my feeble efforts
> inc =: 4 : '((>:(x. get y.))(x.) set y.)'
> dec =: 4 : '((<:(x. get y.))(x.) set y.)'
>
> NB. above gives an error
> inc =: 4 : '( 1&+(x. get y.)),( x.) set y.'
> dec =: 4 : '(_1&+(x. get y.)),( x.) set y.'
> a
> 2 0 0 0 0 0 0 0
> ]a =: 0 inc a
> 1 0 0 0 0 0 0 0 0
>
> NB. OK, it puts the 1: at the 0th position... but adds a zero
>
> inc =: 4 : '( 1&+(x. get y.)),( x.) set y.'
> dec =: 4 : '(_1&+(x. get y.)),( x.) set y.'
> a =: b
> a
> 0 0 0 0 0 0 0 0
> ]a =: 0 inc a
> 1 0 0 0 0 0 0 0 0
> ]a =: 0 inc a
> 2 0 0 0 0 0 0 0 0 0
> ]a =: 0 inc a
> 3 0 0 0 0 0 0 0 0 0 0
>
> NB. in this case, incrementing works but the array lengthens...
>
> Admittedly, trying to do this may be just plain foolish, but what's the
> REAL way to do this?
Your problems seem to stem from inappropriate use of parens.
Your second "inc" function:
inc =: 4 : '( 1&+(x. get y.)),( x.) set y.'
is not supplying a concatenation of value + position to the "set" verb,
but is attempting to concatenate the incremented value with the result of
supplying just a position to "set" (which does nothing). It is not, as
you suggest, appending a zero:
3 inc i.5
4 0 1 2 3 4
2 inc i.5
3 0 1 2 3 4
You can see this more clearly if you use "13 :" instead of "4 :":
13 : '( 1&+(x. get y.)),( x.) set y.'
([: 1&+ get) , set
I think this does what you want:
get =: {
set =: 4 : '({.x.) (}. x.) } y.'
(Note that this version of "set" won't let you get away with short
measure in the left operand)
inc =: 13 : '((>: x. get y.),x.) set y.'
inc
(([: >: get) , [) set ]
3 inc a
0 0 0 1 0 0 0 0
That's if you really want to define "inc" in terms of "get" and "set".
However, you could use the gerund case of amend:
inc =: (>:@get)`[`] }
3 inc a
0 0 0 1 0 0 0 0
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm