Phrases/PrimitiveImplementations

From J Wiki
Jump to navigation Jump to search

Implementation of Certain J Primitives

Some of J primitives are not exactly primitive. Some of them contain bugs, shortcomings and concious trade-offs. Some are not implemented for all arguments.

This page contains definitions, reference implementations or suggested behavior for currenly unimplemented domains for such "primitives".

%: Dyadic, extended

See Essays/IntRoot

A. Dyadic

According to R.Hui:

type  =: 3!:0
boxed =: 32&=@type
pind  =: ]`]`+@.(*@])"0
pfill =: [ ((i.@[-.]) , ]) pind

ord   =: >:@(>./)
base  =: >:@i.@-@#
rfd   =: +/@({.>}.)\.
dfr   =: /:^:2@,/

adot1 =: (base #. rfd)@((ord pfill ])`C.@.boxed) " 1
adot2 =: dfr@(base@] #: [) { ]

See also

? Monadic, Extended

As of J601βn ? applied to on large right arguments yields domain error.

   ?2^31
|domain error
|       ?2^31
   ?_1+2^31
2094548590

The workaround is to use the following verb, which generates a uniformaly distributed random number in the range 0.._1+y. for arbitrary large y. (under assumption that the result of underlying primitive ? is itself uniformly distributed).

dice=: 9999&$: : (4 : 0)"0
  y=. x #.^:_1 y-1
  label_again.
  l=.y =&{. r=.?1+{.y
  while. l *. r<&#y do.
    if. d>f=.y{~_1+#r=.r,d=.?x do. goto_again. end.
    l=.d=f
  end.
  x #. r,?x#~y-&#r
)

Optional left argument specifies chunk size and can be selected to tweak performance.

  • It turns out that optimum for large numbers is achieved with 9999 as left argument, which is quite surprising. -- Andrew Nikitin <<DateTime(2006-06-17T04:03:09Z)>>

Comparisons of non-numeric atoms

J signals domain error if you try to compare character or boxed data with < etc. At the same time /: primitive is somehow capable of comparing nonnumerics in order to grade them. The following adverb unearthes this algorithm.

   ue=:1 : ('u';':';'x u&((/:~x,y)&i.) y') ("0)
   'a' <ue 'b'
1
   'b' <ue 'b'
0
   (<'aardvark') >:ue <'aachen'
1

Roger once gave the reason that /: \: can sort any data, but < <: = ~: >: > can only compare numerics. If you need to compare non-numeric atoms (or items), you may find useful these generalized replacements for the comparison dyads.


Contributed by Andrew Nikitin