On 4 February 2010 09:04, Wardrop <t...@tomwardrop.com> wrote:
> I often myself creating functions which perform a rather clear and
> simple task, but which is hard to describe, either because I don't
> know the term for what I've just implemented, or because the function
> is difficult to summarise in a couple of words. As an example, I've
> just created a function which determines how many times the value n,
> can be divided by the base, until n becomes smaller than the base.
> Here's the implementation...
>
> (defn <insert-name-here> [n base]
>  (loop [n n count 0]
>    (if (< n base)
>      {:val n :count count}
>      (recur (float (/ n base)) (inc count)))))
>
> This can be used among other things, to determine how to format bytes.
> Say I have a file that's 6,789,354 bytes, and I want to display that
> in a more readable manner, I could use my unnamed function like so
> (<unnamed> 6789354 1024), and get a new appropriately rounded number,
> including the number of times it has been rounded, which I can use the
> pick the appropriate suffix from a list ("Bytes", "KB", "MB", "GB",
> "TB).

I would probably split that up:

The division can just use /, so no need for a separate function.
The rest can be done like this:

(defn logn [n x]
  (/ (java.lang.Math/log x) (java.lang.Math/log n)))

Then you could have a function that formats file sizes:

(defn format-file-size [num-bytes]
  (let [base 1024
        val (float (/ num-bytes base))
        times (int (logn base num-bytes))]
...)

Not sure if that helps with your general question, though :)

> I mean, what the hell would you name this function, or would you not
> create such an obscure and generalised function to start with?

-- 
Michael Wood <esiot...@gmail.com>

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

Reply via email to