On 29 May 2010 14:19, WoodHacker <ramsa...@comcast.net> wrote:
> I'm working on  a simple imaging problem.   I want to copy an array of
> pixels to an image buffer.   That means that I have to deal both with
> an array and a matrix (x and y).   As I go along my array, each time x
> reaches the end of a line in the matrix I have to set it back to zero
> and increment y.
>
> I can find no simple way to do this without getting a compile error.
> Can someone show me how to do this?

You could use loop/recur. The following code is closest in structure
to the pseudo code you supplied:

  (loop [x 0, y 0, k 0]
    (when (< k 256)
      (write-buffer x y (value k))
      (if (= x 16)
        (recur 0 (inc y) (inc k))
        (recur (inc x) y (inc k)))))

However, there are more concise methods of programming the same thing.
For instance, we don't need to bother incrementing x and y; we can
calculate them on the fly from k using modulus (mod) and quotient
(quot):

  (loop [k 0]
    (when (< k 256)
      (write-buffer (mod k 16) (quot k 16) (value 16))
      (recur (inc k))))

Now we just have a single loop with a single incrementing variable, k.
This is a common pattern, and there is a macro called "dotimes" in
clojure.core that implements that pattern:

  (dotimes [k 256]
    (write-buffer (mod k 16) (quot k 16) (value 16)))

- James

-- 
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