Phrases/Definitions

From J Wiki
Jump to navigation Jump to search

Compact Verb Definitions

In APL literature a compact one-line definition style was used with α and ω for x and y arguments. It was implemented with a helper "DEF" mode in the session. Here's a J variant of such mode. [{{#file: ""}} Download script: ]

dltb=: #~ ([: (+./\ *. +./\.) ' '&~:)
splitstring=: #@[ }.each [ (E. <;.1 ]) ,

defn=: 1 : 0
  for_i. <;._2 (0 : 0) do.
    'nm df'=. '=:' splitstring >{.'NB.' splitstring >i
    'mn dy'=. dltb each 2 {. ' : ' splitstring df
        if. 0=#dy do. (nm)=: 3 : mn
    elseif. 0=#mn do. (nm)=: 4 : dy
    elseif.       do. (nm)=: 3 : (mn;':';dy) end.
  end.
  i.0 0
)

Note the "defn" mode works both in scripts and in interactive sessions.

Examples:

'Arithmetic' defn                    NB. enter "defn" mode
  add=:  : x+y           NB. addition
  pow=:  ^y : x ^ y      NB. power
  sqr=:  y pow 2
  sqrt=: y pow 0.5
)
                                     NB. exit the mode

which results in the following entries

   add
4 : 'x+y'
   pow
3 : 0
^y
:
x ^ y
)
   sqrt
3 : 'y pow 0.5'
   sqrt 2
1.41421

See Also

Contributed by Oleg Kobchenko