<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Clojure Q&amp;A - Recent questions tagged declare</title>
<link>https://ask.clojure.org/index.php/tag/declare</link>
<description></description>
<item>
<title>what happens if a variable is declared lexical but defined dynamically</title>
<link>https://ask.clojure.org/index.php/10846/what-happens-variable-declared-lexical-defined-dynamically</link>
<description>&lt;p&gt;The following two code snippets behave very differently, depending only on the order you define the functions.   I find this behavior surprising, and probably not intended.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(ns jimka-test
  (:require [clojure.pprint :refer [cl-format]]))

(declare f)

(defn g []
  (map f '(1 2 3)))

(def ^:dynamic f (fn [x] (* x x)))

(defn h []
  (assert (= (g) '(1 4 9)))
  (binding [f (fn [x] (+ x x))]
    (assert (= (g) '(2 4 6))
            (cl-format false &quot;(g) returned ~A&quot; (g)))))

(h)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Now swap the order of definitions of &lt;code&gt;f&lt;/code&gt; and &lt;code&gt;g&lt;/code&gt;.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(ns jimka-test
  (:require [clojure.pprint :refer [cl-format]]))

(declare f)

(def ^:dynamic f (fn [x] (* x x)))

(defn g []
  (map f '(1 2 3)))

(defn h []
  (assert (= (g) '(1 4 9)))
  (binding [f (fn [x] (+ x x))]
    (assert (= (g) '(2 4 6))
            (cl-format false &quot;(g) returned ~A&quot; (g)))))

(h)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;My suggestion is that if a variable is declared non-dynamic, then a later definition as dynamic should issue a warning.&lt;/p&gt;
&lt;p&gt;This issue was also discussed &lt;a rel=&quot;nofollow&quot; href=&quot;https://clojureverse.org/t/string-idiosyncrasy-of-the-compiler/7909/10&quot;&gt;on clojureverse&lt;/a&gt;&lt;/p&gt;
</description>
<category>Compiler</category>
<guid isPermaLink="true">https://ask.clojure.org/index.php/10846/what-happens-variable-declared-lexical-defined-dynamically</guid>
<pubDate>Fri, 23 Jul 2021 17:59:04 +0000</pubDate>
</item>
</channel>
</rss>