Scope modifiers: Difference between revisions

Content added Content deleted
(→‎{{header|R}}: Linked to an enlightening blog post.)
(→‎{{header|Common Lisp}}: global functions within LETs are rarely used. Replaced with local function.)
Line 184: Line 184:


(let ((shape "triangle") (*bug* "ant"))
(let ((shape "triangle") (*bug* "ant"))
(defun speak ()
(flet ((speak ()
(format t "~% There is some ~A in my ~A!" *bug* shape))
(format t "~% There is some ~A in my ~A!" *bug* shape)))
(format t "~%Put ~A in your ~A..." *bug* shape)
(format t "~%Put ~A in your ~A..." *bug* shape)
(speak))
(speak)
(let ((shape "circle") (*bug* "cockroach"))
(format t "~%Put ~A in your ~A..." *bug* shape)
(speak))))</lang>


The 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...
<pre>Put ant in your triangle...