To guard against NPEs, align-to-tick-size should be

(defn align-to-tick-size
  [tick-map value]
  (if-let [tick-size (get-tick-size tick-map value false)]
    (let [remainder (mod value tick-size)]
      (if (zero? remainder)
        value
        (* tick-size ((if (>= remainder (/ tick-size 2)) inc identity)
(quot value tick-size)))))
    value))

On Jan 23, 11:18 am, Eugen Dück <[email protected]> wrote:
> Anyone who has seen the subject implemented in Java/Swing might have
> been stunned by the hundreds of lines of code that were deemed
> necessary for it, with their appropriate share of bugs. (And an
> implementation I've seen in C#/NetAdvantage was even worse, which was
> less related to the language itself, as to the GUI toolkit)
>
> I knew this could be done way more elegant, but I was surprised it can
> be done THIS nicely - if done in clojure. And if you think this can be
> improved further or find any bugs, shoot!
>
> Example: Prices for Japanese stock have a step size of
>     1 in the interval [0,3000],
>     5 in the interval (3000,5000],
>     ...
>
> An easy way to model that would be a sorted map:
>
> (def japanese-stock-tick-map
>      (sorted-map
>            0      1
>         3000      5
>         5000     10
>        30000     50
>        50000    100
>       300000    500
>       500000   1000
>      3000000   5000
>      5000000  10000
>     30000000  50000
>     50000000 100000))
>
> Figuring out the step size - which on the interval edges depends on
> whether you go up or down - can be done like this:
>
> (defn get-tick-size
>   [tick-map value go-up?]
>   (second (first (rsubseq tick-map (if go-up? <= <) value))))
>
> Aligning an arbitrary value to the closest valid number (if
> necessary):
>
> (defn align-to-tick-size
>   [tick-map value]
>   (let [tick-size (get-tick-size tick-map value false)
>         remainder (mod value tick-size)]
>     (if (zero? remainder)
>       value
>       (* tick-size ((if (>= remainder (/ tick-size 2)) inc identity)
> (quot value tick-size))))))
>
> Now implementing the SpinnerModel is trivial (which is why I will not
> copy it here, but leave it onhttp://dueck.org/tick/tick-size-spinner.html
> in a simple demo for anyone to try out).
>
> You're the man, Rich!

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to