Home > database >  Writing custom verbs in J
Writing custom verbs in J

Time:11-06

When you write your custom verbs(functions) should you use the following convention:

convert degrees fahrenheit to celsius.

   centigrade =: 3 : 0
t1 =. y - 32
t2 =. t1 * 5
t3 =. t2 % 9
)

Alternatively, I have seen this:

ftoc=:(5 % 9)* (-&*32)

Is it necessary to use 3 : 0 and y in first example. What general guidelines should one follow?

CodePudding user response:

The multi-line definition is from the Primer and is intended to show how multi-line explicit definitions are defined and how they work with the debugger. It is NOT an example of good programming practice.

With a bit of experience you would write:

   f=: 3 : '9%~5*y-32'
   f _40 32 212
_40 0 100

This could also be done tacitly (without explicit use of y).

   g=: 13 : '9%~5*y-32' NB. get tacit from explicit 
   g
9 %~ 5 * 32 -~ ]
   g _40 32 100
_40 0 37.7778

CodePudding user response:

The format displayed in the primer (i.e. the indentation) is a result of defining the verb in the Terminal with its 3-space indent (as opposed to how it would be formatted in a script. Below are a number of ways of defining verbs. There isn't a single accepted "good style". The "best" method probably depends on the use-case and user preference.

"Classic" explicit

f=: 3 : 0
  9 %~ 5 * y -32
)

Variables are referenced explicitly. Good for longer, more complex verbs with multiple variables. The key symbol/primitive here is the conjunction : or def. See the JWiki page for a more exhaustive list of its forms.

Novice-friendly explicit

f=: verb define
  9 %~ 5 * y -32
)

Same as "classic" but with some defined names to help with readability.

"String" explicit

f=: 3 : '9 %~ 5 * y - 32'

One-liner version of explicit, but can get ugly if the verb includes strings/literals that are delimited with single-quotes. Also doesn't play nice with syntax-highlighters.

Tacit

f=: (5%9) * -&32
f=: 9 %~ 5 * 32 -~ ]   NB. alternative that ignores any left argument

Also known as point-free style, tacit verbs don't explicitly refer to their arguments. Great for smaller, simpler, well-defined verbs with one or two arguments. Can be more performant where a verb is invoked multiple times because it is only parsed once. Potentially defined and used within an explicit definition.

Direct Definition

f=: {{ 9 %~ 5 * y -32 }}

Direct definition was introduced in J9.02. It is a cleaner, more conventional syntax for explicit definition that enables single-line explicit definitions that play nicely with syntax-highlighters, as well as longer, more complex verbs with embedded explicit definitions.

  • Related