Posts Tagged ‘tutorial’

“The first rule of macro club is: Don’t write macros”

I wrote this originally as an answer to a StackOverflow question. But the question got closed by some trigger-happy mods before I clicked post. How unfriendly!

Anyway, in case it is useful to people wondering when they should and shouldn’t use macros, I thought I would post it here instead….

(more…)

Advertisements

Creating a glow effect

Posted: October 4, 2012 in clisk, Uncategorized
Tags: , ,

Quick tutorial on how to create a “glow” effect for any image / shape in Clojure with Clisk.

Image

The idea behind the glow effect is to do the following:

  • Start with an image that has an alpha channel indicating which areas are transparent
  • Extract the alpha channel to get the pure shape of the object
  • Create a glow effect by applying a blur filter to the shape
  • Superimpose the original object on top of the glow

(more…)

I discovered an interesting trick today which I thought worth sharing – you can add a side effect to the end of a sequence in Clojure which will only get called after the sequence is fully consumed for the first time.


(defmacro on-consumed [seq code]
  `(lazy-cat ~seq (do ~code nil)))

(def coll
     (on-consumed [1 2 3] (println "DONE")))

(take 2 coll)   ;; not fully consumed
=> (1 2)

(take 3 coll)   ;; not fully consumed (not gone past third item)
=> (1 2 3)

(take 4 coll)   ;; fully consumed past end of sequence
=> (1 2 3)
DONE            ;; printed to *out*

(take 4 coll)   ;; fully consumed for second time, no side effect
=> (1 2 3)

So how does this work?

(more…)

The sequence abstraction brings me much joy.

In honour of this humble construct I thought I’d write a quick blog post: covering what it is and some examples of how elegant it can make your Clojure code.

(more…)

Truthiness tricks

Posted: August 20, 2012 in Uncategorized
Tags: , , ,

In Clojure, any value can be considered as “truthy” or “falsey” for the purposes of a conditional expression.

The rule is very simple:

  • nil and false  – are “falsey”
  • everything else – is considered “truthy”

This rule may seem strange if you come from a world with a strictly defined boolean type (like Java). But it turns out that it enables some neat tricks in Clojure code that are well worth knowing.

(more…)

It’s always good practise to define named constants rather than embedding “magic numbers” in your code.

If you are going to do this, then there are some important tricks to make sure that you get the best possible performance out of your constants.

(more…)

Recently I’ve found myself using keyword arguments more and more in Clojure so this post is about how to use keyword arguments and their pros and cons.

(more…)