Clojure Snippets

(doseq [x ["a" "b" "c"]]
  (intern *ns* (symbol x) 666))

The above will dynamically define variables (a, b and c and set them to 666), ripped from this stackoverflow question.

(ns some.namespace
   (:require [clojure.contrib.str-utils2 :as string]))

(defn ip-str-to-int [str-ip] 
   (let [nums (vec (map read-string (string/split str-ip #"\.")))]
         (* (nums 0) 16777216) 
         (* (nums 1) 65536) 
         (* (nums 2) 256) 
         (nums 3))))

The above will convert a string representation of an IP number to its integer form. Note how we make use of the string utils library no2 and read-string in order to first split the ip string up into a list with strings and then converting the strings into integers. Finally we use vec to convert the list into a vector and the fact that (vector pos) can be used to retrieve the value at pos.

(defn stamp-today  []
  (let [cur-time (time/now)]
       (time/year cur-time)
       (time/month cur-time)
       (time/day cur-time))))))

The above will get today’s UNIX time stamp where time is clj-time. Good when storing data that needs to be indexed by day.