Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Rob's answer is of course correct; I'm posting this one in response to the OP's comment on it -- perhaps it might be helpful in implementing the required functionality with <code>deftype</code>.</p> <p>I have once written an implementation of a "default map" for Clojure, which acts just like a regular map except it returns a fixed default value when asked about a key not present inside it. The code is in <a href="http://gist.github.com/468332" rel="nofollow noreferrer">this Gist</a>.</p> <p>I'm not sure if it will suit your use case directly, although you can use it to do things like</p> <pre><code>user&gt; (:earth (assoc (DefaultMap. 0 {}) :earth 8000000000)) 8000000000 user&gt; (:mars (assoc (DefaultMap. 0 {}) :earth 8000000000)) 0 </code></pre> <p>More importantly, it should give you an idea of what's involved in writing this sort of thing with <code>deftype</code>.</p> <p>Then again, it's based on <code>clojure.core/emit-defrecord</code>, so you might look at that part of Clojure's sources instead... It's doing a lot of things which you won't have to (because it's a function for preparing macro expansions -- there's lots of syntax-quoting and the like inside it which you have to strip away from it to use the code directly), but it is certainly the highest quality source of information possible. <a href="http://github.com/clojure/clojure/blob/1.2.0/src/clj/clojure/core_deftype.clj#L134" rel="nofollow noreferrer">Here</a>'s a direct link to that point in the source for the 1.2.0 release of Clojure.</p> <p><em>Update:</em></p> <p>One more thing I realised might be important. If you rely on a special map-like type for implementing this sort of thing, the client might <code>merge</code> it into a regular map and lose the "defaulting" functionality (and indeed any other special functionality) in the process. As long as the "map-likeness" illusion maintained by your type is complete enough for it to be used as a regular map, passed to Clojure's standard function etc., I think there might not be a way around that.</p> <p>So, at some level the client will probably have to know that there's some "magic" involved; if they get correct answers to queries like <code>(:mars {...})</code> (with no <code>:mars</code> in the <code>{...}</code>), they'll have to remember not to <code>merge</code> this into a regular map (<code>merge</code>-ing the other way around would work fine).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload