Minimal example: I have (defstruct st :a :b) and always when I define
something like this (struct-map st :a 4) omitting :b I would like to
have :b set automatically to 0.0 instead having nil.
Is this possible?
--
Manfred
user=> (defstruct St :a :b)
#'user/St
user=> (defn st ([a] (struct St a 0.0)) ([a b] (struct St a b)))
#'user/st
user=> (st 5)
{:a 5, :b 0.0}
> No, but if you need to do that, then you can do what deftype sort-of
> does:
>
> user=> (defstruct St :a :b)
> #'user/St
> user=> (defn st ([a] (struct St a 0.0)) ([a b] (struct St a b)))
> #'user/st
> user=> (st 5)
> {:a 5, :b 0.0}
>
>
Thanks for this.
Now I tried a different way:
(defstruct st :a :b)
(defn my-struct-map [s & inits]
(let [sm (struct-map s inits)]
(if (= nil (sm :b))
(assoc sm :b 0.0)
sm))
)
Unfortunately, the part sm (struct-map s inits) doesn't work. I have no
idea what is wrong with my code.
--
Manfred
On Sat, Mar 6, 2010 at 20:36, Manfred Lotz <manfre...@arcor.de> wrote:
> Now I tried a different way:
>
> (defstruct st :a :b)
>
> (defn my-struct-map [s & inits]
> (let [sm (struct-map s inits)]
> (if (= nil (sm :b))
> (assoc sm :b 0.0)
> sm))
> )
>
> Unfortunately, the part sm (struct-map s inits) doesn't work. I have no
> idea what is wrong with my code.
The problem is with the inits argument passed to struct-map. Your
method will pass a sequence. For instance, if you invoke
(my-struct-map st :a 1 :b 2), struct-map is invoked like this:
(struct-map st (:a 1 :b 2)).
I didn't know how to fix this myself, but nteon on the IRC helped out
and pointed me to apply. So, this definition now works for me:
(defn my-struct-map [s & inits]
(let [sm (apply struct-map s inits)]
(if (= nil (sm :b))
(assoc sm :b 0.0)
sm)))
Hope that helps,
Mike
depending on your application you might use defnk (http://
richhickey.github.com/clojure-contrib/def-api.html#clojure.contrib.def/
defnk) to build your struct with default values.
Benjamin
> Hi,
>
> On Sat, Mar 6, 2010 at 20:36, Manfred Lotz <manfre...@arcor.de>
> wrote:
> > Now I tried a different way:
> >
> > (defstruct st :a :b)
> >
> > (defn my-struct-map [s & inits]
> > (let [sm (struct-map s inits)]
> > (if (= nil (sm :b))
> > (assoc sm :b 0.0)
> > sm))
> > )
> >
> > Unfortunately, the part sm (struct-map s inits) doesn't work. I
> > have no idea what is wrong with my code.
>
> The problem is with the inits argument passed to struct-map. Your
> method will pass a sequence. For instance, if you invoke
> (my-struct-map st :a 1 :b 2), struct-map is invoked like this:
> (struct-map st (:a 1 :b 2)).
>
Oh yes, I was not aware of this, although it is pretty logical.
> I didn't know how to fix this myself, but nteon on the IRC helped out
> and pointed me to apply. So, this definition now works for me:
>
> (defn my-struct-map [s & inits]
> (let [sm (apply struct-map s inits)]
> (if (= nil (sm :b))
> (assoc sm :b 0.0)
> sm)))
>
Yep, helped.
--
Thanks,
Manfred