Essays/Scope

From J Wiki
Jump to navigation Jump to search

APL Dynamic Scope

APL uses dynamic scoping, that is arguments and local variables defined in the stack of callees are visible to the caller function, as long as they are not redefined.

A characteristic language with dynamic scoping is LISP.

Apl-scope.png

      OUTER 123
IN OUTER X=123 ONE=11 TWO=22
IN INNER X=456 ONE=12 TWO=22

J Static Scope

In J local names are only visible in the current (explicit) definition.

outer=: 3 : 0
  one=. 11
  two=. 22
  q=.   'in outer y=',(":y)
  q=. q,' one=',(":one),' two=',":two
  smoutput q
  inner 456
)

inner=: 3 : 0
  one=. 12
  q=.   'in inner y=',(":y)
  q=. q,' one=',(":one),' two=',":two
  smoutput q
)

Though global names are visible in any scope.

   outer 123
in outer y=123 one=11 two=22
|syntax error: inner
|   q=.q    ,' one=',(":one),' two=',":two
   two=. 20
   outer 123
in outer y=123 one=11 two=22
in inner y=456 one=12 two=20

See Also


Contributed by Oleg Kobchenko