Phrases/Language Utilities

From J Wiki
Jump to navigation Jump to search

Testing for Empty Operands

NB. Adverb.  Do u, but skip it if y is null
ifany =: ^: (*@#@])
NB. Same if x is nonnull
ifanyx =: ^: (*@#@[)

NB. Conjunction: u unless y is empty; then v
butifnull =: 2 : 'v"_`u@.(*@#@])'
NB. Conjunction: u unless x is empty; then v
butifxnull =: 2 : 'v"_`u@.(*@#@[)'

Various Ways of Naming an Empty List

NB. Empties: select one according to context
NIL =: ''   NB. required argument to niladic function
NILRET =: ''   NB. return from function with no explicit result
NILRETQUIET =: i. 0 0  NB. return to J, without printing
NB. verb to return empty list, to discard the actual returned value
null =: ''"_

Bivalent Conjunction: [x] u v y

When you are creating conjunctions out of other conjunctions, you have to handle the monadic and dyadic cases of the resulting verb. If you have a long sequence of n such conjunctions, and each one refers to its u and v twice, you end up with 2^n copies of the outermost u and v . If your monadic and dyadic forms are related, such that the monad is u v y and the dyad is x u v y, you can code u bivalent v to handle both cases without the combinatorial explosion.

NB. bivalent =: @: : ([. ].)  NB. u v y if monad, x u (v y) if dyad
NB. u v y if monad, x u (v y) if dyad
bivalent =: 2 : 'u@:v : (u v)'

Structural Conjunctions

These conjunctions generalize the hook/fork idea. u xuvy y is the hook (u v); x u ux_vy v y is (u x) v y; etc.

xuvy =: 2 : 'u v'
yuvx =: 2 : '(u v)~'
uy_vx =: 2 : 'v~ u'
ux_vy =: 2 : '(v~ u)~'
vy_ux =: 2 : 'u~ v'
vx_uy =: 2 : '(u~ v)~'

Intolerant e. and i.

NB. Like e. dyadic, but using intolerant comparison.  Faster on lists with identical first elements
in0 =: e.!.0
NB. Like i. dyadic, but using intolerant comparison.  Faster on lists with identical first elements
index0 =: i.!.0

Assembling Results on Lists End-to-End

Use these tools when applying your verb to the items produces results of different lengths, and you want to combine all those results into a list.

NB. Adverb.  Apply u and join the results end to end
endtoend =: 1 : ';@:(<@u)'
NB. Adverb.  Apply u on keys, join results end-to-end
keyetoe =: 1 : ';@:(<@u/.)'
NB. Conjunction, like Cut but put results end-to-end
cutetoe =: 2 : ';@:(<@u;.n)'

One-time Initialization

Use this if you want to avoid changing a variable that's already defined, but you want to initialize it if it's not defined.

NB. Initialize a global, but not if it's already been initialized
NB. Example: 'name' initifundef 5
initifundef =: (, ('_'&([,],[))@(>@(18!:5)@(0&$)) ) ux_vy ((4 : '(x) =: y')^:(0:>(4!:0)@<@[))

See also User:Andrew Nikitin/once