Scope modifiers: Difference between revisions

→‎{{header|Common Lisp}}: global functions within LETs are rarely used. Replaced with local function.
(→‎{{header|R}}: Linked to an enlightening blog post.)
(→‎{{header|Common Lisp}}: global functions within LETs are rarely used. Replaced with local function.)
Line 184:
 
(let ((shape "triangle") (*bug* "ant"))
(defunflet ((speak ()
(format t "~% There is some ~A in my ~A!" *bug* shape)))
(format t "~%Put ~A in your ~A..." *bug* shape)
(speak))
(let ((shape "circle") (*bug* "cockroach"))
(format t "~%Put ~A in your ~A..." *bug* shape)
(speak))))</lang>
 
The global function <code>speak</code> tries to use both <code>*bug*</code> and <code>shape</code>. For lexical scope, the value comes from where the program ''defines'' <code>speak</code>. For dynamic scope, the value comes from where the program ''calls'' <code>speak</code>. So <code>speak</code> always uses the same "triangle", but can use a different bug.
(let ((shape "circle") (*bug* "cockroach"))
(format t "~%Put ~A in your ~A..." *bug* shape)
(speak))</lang>
 
The global function <code>speak</code> tries to use both <code>*bug*</code> and <code>shape</code>. For lexical scope, the value comes from where the program ''defines'' <code>speak</code>. For dynamic scope, the value comes from where the program ''calls'' <code>speak</code>. So <code>speak</code> always uses the same "triangle", but can use a different bug.
 
<pre>Put ant in your triangle...
Anonymous user