Clojure: reduce vs. apply

reduce and apply are of course only equivalent (in terms of the ultimate result returned) for associative functions which need to see all their arguments in the variable-arity case. When they are result-wise equivalent, I’d say that apply is always perfectly idiomatic, while reduce is equivalent — and might shave off a fraction of a … Read more

Generating permutations lazily

Yes, there is a “next permutation” algorithm, and it’s quite simple too. The C++ standard template library (STL) even has a function called next_permutation. The algorithm actually finds the next permutation — the lexicographically next one. The idea is this: suppose you are given a sequence, say “32541”. What is the next permutation? If you … Read more

How to handle java variable length arguments in clojure?

Since Java varargs are actually arrays, you can call vararg functions in Clojure by passing an array. You could convert a Clojure seq (maybe by using Clojure’s variety of variable argument functions) into an array: (TestClass/aStaticFunction (into-array Integer [(int 1),(int 2)])) or (defn a-static-function-wrapper [& args] (TestClass/aStaticFunction (into-array Integer args)) Or make an array and … Read more

A regex to match a substring that isn’t followed by a certain other substring

Try: /(?!.*bar)(?=.*foo)^(\w+)$/ Tests: blahfooblah # pass blahfooblahbarfail # fail somethingfoo # pass shouldbarfooshouldfail # fail barfoofail # fail Regular expression explanation NODE EXPLANATION ——————————————————————————– (?! look ahead to see if there is not: ——————————————————————————– .* any character except \n (0 or more times (matching the most amount possible)) ——————————————————————————– bar ‘bar’ ——————————————————————————– ) end of … Read more

leiningen – how to add dependencies for local jars?

Just use :resource-paths in your project.clj file. I use it, e.g. to connect to Siebel servers. Just created a resources directory in my project directory and copied the jar files in there. But of course you could use a more generic directory: (defproject test-project “0.1.0-SNAPSHOT” :description “Blah blah blah” … :resource-paths [“resources/Siebel.jar” “resources/SiebelJI_enu.jar”]) Then from … Read more

When to use a Var instead of a function?

Yes, a Var in Clojure is similar to a C pointer. This is poorly documented. Suppose you create a function fred as follows: (defn fred [x] (+ x 1)) There are actually 3 things here. Firstly, fred is a symbol. There is a difference between a symbol fred (no quotes) and the keyword :fred (marked … Read more