April 23, 2014

Clojure Weekly, April 23rd, 2014

Welcome to another issue of Clojure Weekly, my small routine blog contribution to the Clojure sphere! These are just a few links, normally 4/5 urls, pointing at articles, documentation, screencasts, podcasts or anything else that attracts my attention. I add a small comment so you can decide if you want to look at the whole thing or not. That’s it, enjoy!

TDD is dead. Long live testing. (DHH) Not strictly Clojure related, but the discussions about TDD vs REPL driven development is still hot in Clojure-land. DHH here is publicly declaring that TDD is dead. I saw the tweets coming from the keynote at RailsConf and I’m looking forward to the Rails community reaction. DHH was never a fan of TDD but he was sort of doing it in the past, without realising exactly what was wrong with that approach. This blog post explains why he now thinks that TDD is just like learning wheels (oh, I so wait for Uncle Bob’s write up!). What’s my take on this? I still start test first, I can’t resist, but I’m much less strict than the past. I quickly abandon it as soon as third party services are invoked, or some piece of infrastructure that requires a lot of stubbing is required (like a rest endpoint for example). This is when I abandon TDD and use the REPL to play with the app. Mind that I’m also using the REPL throughout development, to create the implementation that makes my tests green. Still happy with that, it helps me think and focus, exactly like this weekly writing.

keyword parameters? - Google Groups Old but interesting discussion about named parameters for functions. I already talked about defnk in the past and it was abandoned after migrating out from clojure contrib. Still it is an interesting little exercise to see how simply the feature can be added to the language (something that happened for Ruby properly in 2.0). Rich is showing the code in the last email. With this macro you can define functions that declares parameters with a name and a default. If the last two parameters in the example are not given (or others are given), it takes the default. The only way to change that default is to prefix the keyword to the parameter. The only caveat, at least in this simple implementation, is that the named params need to be at the end.

Decompiling Clojure I - Interrupted This is the start of a very interesting and well written series of article about Clojure internals, the relationship with Java and the produced byte code. It doesn’t assume previous knowledge of any of the above which is very good if you never decompiled a class file. The last part explains the additional information that the compiler can add to the byte code to help the JVM during debugging (for example). Next instalment will be about the compiler and reader and I’m looking forward to it.

ClojureDocs - clojure.core/or “or” can be used the standard way as in many other languages. But since nil is false in predicates, “or” can be also used to handle those frequent cases where some parameter can be nil and a default can be provided. (or mime “application/html”) for example could be used to accept a given mime variable or use an application/html default when mime is nil. That is equivalent to the more verbose (if mime mime “application/html”) which is not as nice to read.

The rise of functional programming in Banks | Oxford Knight Blog An interesting non-technical point of view from a recruitment firm that is investing a lot in the field of functional programs. The post sates that the raise of FP especially in banks since 2006 can be related to the fact that it models concurrency better, it models math better and that skills learned on the JVM (of course Scala and Clojure only) can be easily sold to other OO-based businesses. The last part reports back on teams adopting the main five FP languages: scala, clojure, haskell, ocaml and F#. No mentions for Erlang (always talking about banks, hedge funds and investment banks in general).

Comments (View)
April 15, 2014

Clojure Weekly, April 15th, 2014

Welcome to another issue of Clojure Weekly, my small routine blog contribution to the Clojure sphere! These are just a few links, normally 4/5 urls, pointing at articles, documentation, screencasts, podcasts or anything else that attracts my attention. I add a small comment so you can decide if you want to look at the whole thing or not. That’s it, enjoy!

Dissecting Clojure Reducers This talk I gave at Strangeloop 2013 is finally up on InfoQ. I’m still convinced live coding sessions are possible (and will take again the risk in the future if necessary), but this is an example of screwing up and being unable to recover :( The entire working REPL session is published here https://github.com/reborg/talk-strangeloop2013/blob/master/src/strloop2013/core.clj if you want to see how it was expected to finish!

Cognicast :: Podcast I’ve managed to listen to only half of it, but it’s already dense enough to deserve attention. React maintains a virtual DOM representation. Components change the DOM without direct manipulation. Changes are propagated down to the virtual DOM and when it’s time to synch a diff is calculated and the real DOM is updated. OM implements a similar mechanism but since it is using the ClojureScript immutable data structures, it can check equality on identity of objects instead of values, with immediate speedup as a result.

clojure.core - Clojure v1.6 API documentation mapv has the same semantic of map but it returns a vector instead of a seq. It resolves to into for all cases where the inputs are more than one. But possibly the most common case is mapv over a single collection. In this case instead of plain into [] an optimised version makes use of transients. Click on “source” to see it in core.clj. Basically: reduce over coll starting from a transient seed, updating in place the results with the transformation and go back to persistent data structures at the end. The creation of the final vector happens outside a persistent data structure, when you can safely assume it is safe to mutate. This is a lesson from std-lib: idiomatic clojure often paysoff in several ways.

weavejester/lein-generate This is brilliant. I’m constantly repeating action like: create a namespace/test pair files from existent ones, change ns names to the new one, require the ns from the test blah blah. If you TDD you know what I mean :) But the plugin offers extendibility as a feature. I’m pretty sure I’ll come up with other repetitive project actions that can be incorporated.

ClojureDocs - clojure.core/dorun doall, doseq and dorun all provide a way to realise lazy sequences, but there are quite important differences. If the only goal is to realise the sequence for side effects, dorun is the preferred, because it does not retain the collection in memory. For some additional degree of sophistication, doseq also offers bindings and destructuring like for and still not return (hence retain) the collection in memory. doall should be used only when the collection should fully realise before leaving some “connection” context, because the element in it are dependent on that. doall often happens on result sets from 3rd party services that need to release the connection before being used.

ClojureDocs - clojure.core/format Format is quite powerful printing function. You can use it with positional args with %s, but I was unaware of other interesting features like padding capabilities. This is one of those things that when you don’t know you end up rolling your own string padding feature (and that can be a 2 hours Yak shaving task).

Comments (View)
April 9, 2014

Clojure Weekly, April 9th, 2014

Welcome to another issue of Clojure Weekly, my small routine blog contribution to the Clojure sphere! These are just a few links, normally 4/5 urls, pointing at articles, documentation, screencasts, podcasts or anything else that attracts my attention. I add a small comment so you can decide if you want to look at the whole thing or not. That’s it, enjoy!

zcaudate/lein-repack · GitHub Interesting idea. The goal: avoid copy paste for functional re-use. The background: we all seem to have an clj-util library, where we store functional bits across projects that are generic enough to be reused elsewhere. At the same time this clj-utils is “personal” and when I find someone else snippet I’d like to use I don’t want to have a dependency just for that. So, copy paste into my clj-utils! (with attribution). What if instead there was a “function” repository? What if the granularity of re-use was the require of a single function from another library? While we are thinking about it, lein-repack takes that a step further by treating namespaces in a project as separate deployable entities (that is, producing a separated set of libraries). With a little bit of namespace design, lein-repack makes it possible to require just a namespace of what used to be an entire project require. Still a project.clj line in dependencies, but a step further into a better re-use.

Tutorial on Good Lisp Programming Style - Peter Norvig Very lispy indeed. But tips on functional abstraction applies to Clojure as well. It is also a must read in terms of principles of good style in programming, expressing intention and good functional engineering in general. The format is also very readable, a mix between a slide-based presentation and a full paper. The bit I enjoyed the most is the rule of english translation for functional decomposition: 1. start with a sudo-code english description of the algorithm 2. translate to working code 3. translate code back into english 4. compare 3 to 1. If 3 is much more articulated than 1, you’re missing functional abstractions (i.e. extract function). 1 should read as 3 with all complexity extracted into helper functions.

The Clojure REPL; a blessing and a curse This article by Martin Trojer really resonates with me. I’m very happy to have a component-based lifecycle for my Clojure projects. At the same time, when I first heard about Stuart Sierra Clojure reloaded workflow, I thought that the effort wasn’t entirely justified. The component workflow to keep the REPL alive at all costs doesn’t seem to be scaling over a certain level and maybe it is time to re-design the Clojure static initialisation context in a different, more lazy, way. Keep in mind that the problem is not Clojure at all, it’s a fairly fast and close to Java performance env. The main problem seems to be the development lifecycle.

Why is Clojure bootstrapping so slow? This article is a fairly detailed analysis of the Clojure bootstrap time. Clojure projects are reaching a “critical” size in live environments, where bootstrapping with all the dependencies can take up to a minute or more (I’m not talking about the hello world used as an example in this article). Clojure component-based workflows are helping mitigate the problem, but restarting the REPL for development is still a frequent operation. So what is the problem exactly? Clojure bootstrap is basically a giant Java static initialisation context. All Symbols to hold values or functions are first defined (metadata included) and then Vars are initialised so they point to the specific symbol (function or value). This happens for each var declaration in clojure.core plus a few helper namespaces that are loaded on a side. Each namespace results in a Java class byte code (loaded at runtime or AOT compiled), its long static initialiser and one inner class for each fn. The main take away of this analysis is that what is not used should be loaded lazily.

clojure/clojure-clr · GitHub The Clojure repo targeting the CLR and written in C# is far from being dormant. And despite the Java brother is getting all the of the attention, this is a remarkable achievement. The .NET version of Clojure started side by side with the Java version in 2006 then kept in sync, starting a few years ago, apparently by Dave Miller alone! Dave is also porting all the other important contrib libraries like core.async. A dedicated mailing list was recently started.

Comments (View)
April 1, 2014

Clojure Weekly, April 1st, 2014

Welcome to another issue of Clojure Weekly, my small routine blog contribution to the Clojure sphere! These are just a few links, normally 4/5 urls, pointing at articles, documentation, screencasts, podcasts or anything else that attracts my attention. I add a small comment so you can decide if you want to look at the whole thing or not. That’s it, enjoy!

ClojureDocs - clojure.core/destructure Destructure is not well documented. Maybe Rich has reasons for that, like an unstable interface, but it’s widely used in the Clojure codebase. I think it is useful to try out destructuring without the need to setup a let form for it. You can see if it’s doing what you expect at the repl quite easily. Destructure returns a vector of symbols unevaluated-forms pairs. The pair can be actually executed by internalising the symbol using the eval of the form as the value.

The Future of JavaScript MVC Frameworks Took the time to read through the OM rationale blog post. I still need to understand all the implications of dom rendering and manipulation, but the net effect seems to be when immutable data structures can be always analysed top to bottom in logN time. Facebook React offers the idea, that only sub-trees of the DOM should be processed to reflect changes but does that ineffectively using mutable JS objects. Om ads ClojureScript immutable data structures on top of that increasing speed, simplicity and evolvability. Present here are is also the speed gain you get if instead of plain react Om is used. It just seems the perfect use case for real functional data structures.

Amazing LISP Books living again in Clojure | Cool Pacific Nice list of “lambda-books” re-written or narrated again with examples in Clojure. I have my copy of Practical Common Lisp that I read sometimes to clarify functional concept. I’m also constantly working on SICP and I sometimes experiment with them in Clojure. I didn’t know Stuart Halloway did a series of blog post porting it to Clojure, good to know. Also didn’t know about the little Schemer in Clojure, I’m curious to read the Y-Combinator chapter 9.

clojure - How to set a dynamic var in another namespace - Stack Overflow This little answer by Chris Houser summarises pretty much everything you need to know when using dynamic vars. alter-var-root works for dynamic vars as well and when used it changes the root for all the references to the var across all threads. There are very few cases in which this could be useful, for example if you store your config in memory and you suddenly need to change it for all the running threads at once.

Clojure/West 2014 - YouTube Huge list of all the latest and the greatest Clojure/West 2014 available on youtube. Looking forward to watch a few of them: Daniel Solano about Clojure internals, David Nolen (curious to understand the buzz around Om) Timothy Baldrige about the clojure AST rendering, David Greenberg on interactive Datomic tooling, and much more. Wondering who did the final keynote. (BTW: interested in watching while commuting offline? Look at http://rg3.github.io/youtube-dl)

ClojureDocs - clojure.core/proxy Proxy is a function that lets you generate a Java class on the fly. If you ever heard of DynamicProxy in Java this is similar with a twist, considering it also allows to extend concrete classes (thanks to ASM I suppose). For example: (def my (proxy [Exception] [“custom message”])) generates a new instance of a class extending exception and invoking super constructor with a custom message. You can now (throw my) as excepted. More complicated stuff is possible, for example implementing methods from an interface and so on.

[ANN] Clojure 1.6 - Google Groups It is a major version release, the list of changes is impressive, but still it doesn’t sound like a ground breaking Clojure release like 1.5 was for example. To note: the new hashing algorithm are going to improve performance in some areas, especially where collections are used as keys in maps. A consolidated Java interface is out (that is, what as a Java programmer you’re supposed to use to invoke Clojure). Many more bug fixes, performance improvements (I noticed a 2011 ML thread related to a System.currentTimeMillis() left in the code unused and finally landed into the main branch :)

The Bipolar Lisp Programmer Interesting discussion about what ultimately determined Lisp limited success. Mark Tarver describes the negative attitude, a typical behaviour of creative people, to burst into high productive periods followed by deep lack of interest (the bipolar aspect of it). Lisp attracted this kind of people because it was extremely easy to put together a throw-away design and at the same time it was very easy to abandon an idea without making it “world-ready”. Lispers originated many of the ideas that we take for granted today: windowing, personal computing, garbage collection and much more. But those ideas weren’t executed carefully enough to survive the industrial world, forcing managers in the industry to prefer easily interchengeable generic developers instead of bipolar lisp programmers. There is also an interesting social aspect of the bipolar programmer: complexity generated by C-based languages and their verbosity tends to produce more communicative teams (literally to search for help).

Comments (View)
March 25, 2014

Clojure Weekly, March 25th, 2014

Welcome to another issue of Clojure Weekly, my small routine blog contribution to the Clojure sphere! These are just a few links, normally 4/5 urls, pointing at articles, documentation, screencasts, podcasts or anything else that attracts my attention. I add a small comment so you can decide if you want to look at the whole thing or not. That’s it, enjoy!

scgilardi/slingshot Slingshot enhances Clojure error handling through a simple addition (that I never thought about, but it really makes sense). With Slingshot you are able to throw any (Clojure-Java) object, not just those inheriting from Throwable. It makes sense because many times to give more context to an exception I find myself composing a formatted string with all the information I need to send to the Exception constructor. Superpowers come using try+ and throw+ to enable throwing for example a Clojure map. Too bad this is not part of Clojure core: having to import that lib seems a little too much overhead.

#clojure log - Apr 28 2008 For the oldies but goodies section this week, I found this little snippet browsing an old #clojure IRC log (and BTW this link is a very useful sever that saves the entire chat history for posterity). Rich replying in the chat how to inspect a namespace for public functions that can be easily enhanced to filter by regex: (filter #(re-matches #”.print." (str %)) (keys (ns-publics (find-ns ‘clojure.core)))) will find all the function containing "print" in the core namespace. Use it when autocompletion is not enough!

Clojure class inheritance diagram This class diagram is old, when Clojure was still released as a timestamped zip file. Many of those classes and interfaces are still present today. The interesting bit is the fact that Clojure at its core was modelled through careful object orientation. More precisely, this diagram shows how the concepts of the Lisp language were modelled through OO: Symbols, Keywords, Namespaces a Callable AFn and so on. Is like teaching Java how to be a Lisp :)

~/.lein/profiles.d profiles in Leiningen Couldn’t find a decent explanation of this on the Leiningen readme (where it is just generally saying these profiles will be merged with the main profile). There are many places where you can define a profile in Leiningen: you have your project.clj, /etc/leiningen/profiles.clj, ~/.lein/profiles.clj and also ~/.lein/profiles.d/<younameit>.clj Got my answer on the issue that generated the feature. It is just the only way of all the specified place above where you don’t need to explain how to open a file to alter profiles definition if you want to distribute a profile as part of your Clojure app.

AsmReflector throws exceptions on JDK8 - Clojure JIRA The JDK 8 is out. I’m curious to know how that affects Clojure but still have to try myself. Apparently the only minor annoyance around seems to be on the ASMReflector, an util class used to manipulate the Java classes at runtime through reflection. But as far as I can see, the ASM Reflector is not the default and the new version of ASM 5 seems to solve the problem. Another question I have is if from the point of view of the byte code manipulation and generation, there is any advantage with the introduction of the new java closures. I mean, do we have now an alternative to compile clojure functions down to classes or is there now a different way to do it? Not sure.

cursive clojure Cursive is yet another Clojure IDE (in a good sense). At the moment it replaces La Clojure as the reference Clojure plugin for IntelliJ 13.x Not sure if it will be also an independent executable. It works flawlessly in IntelliJ despite its alpha status, where I mostly use it on 3rd parties project exploration, since debugging is still a much better experience outside vim/emacs these days. Installation requires to add a new repo to the System->plugins settings and after that you just import existing projects by pointing at project.clj. To run an app, create a running config, optionally ticking “running in the REPL” (where you can interact with the running app in debug mode). Sweet.

Dead-simple threading with functions, in Clojure This is an interesting point of view and also a warning (imho). Threading functions have limitations and several libraries around are offering more powerful alternatives. At the same time threading functions were designed with simplicity in mind, to replace a difficult to read “nesting” into a linear invocation. They are great at that and if you find that you’re constantly fighting with limitations like the position of the threaded collection (for -») or item (for ->) it’s maybe just the case to avoid threading. This article shows how threading can be replaced effectively with higher order functions instead of using a 3rd party library.

EdnReader.java at master · clojure/clojure For our weekly exploration into Clojure sources, this time I’m linking here the EdnReader. In many ways this is similar to the bigger bro, the Clojure compiler. Recognized forms are static declarations at the top, each one handled by an inner class that knows how to parse a specific end form given a reader. Inner classes are AFn extensions, an abstraction on top of some behaviour that can be invoked (pervasive in Clojure). The core is the “read” method that goes through all chars in the input stream analysing them one by one and invoking specific behaviours when a special form-init tag is found. The output is the interpreted Clojure equivalent.

Comments (View)
March 18, 2014

Clojure Weekly, March 18th, 2014

Welcome to another issue of Clojure Weekly, my small routine blog contribution to the Clojure sphere! These are just a few links, normally 4/5 urls, pointing at articles, documentation, screencasts, podcasts or anything else that attracts my attention. I add a small comment so you can decide if you want to look at the whole thing or not. That’s it, enjoy!

cemerick/friend An authorisation/authentication framework for Ring based Clojure web app. Friend has a terse API which is quite easy to understand and yet is as powerful as other full-fledged security frameworks. You can attach roles to user and use the same roles when defining routes. Routes and their HTTP verbs are effectively unique ids for an action and with Friend you decide what roles can perform the action (i.e. /docs is accessible to ::guest but /private only to ::admin). Friend also contains other DSL-ish APIs to indicate protected channels (routes that should be redirected if accessed with the wrong protocol) and supports b-crypt encryption.

ClojureDocs - clojure.core/rand-nth Hopefully I’m here again to prevent you another waste of time :) I did the very first time, inventing my own how to access a collection by a random index kind of thing. Sorry, the std-lib got that already and is called rand-nth. That delegates to the old faithful java Math.Random()

core.clj if-let multiple arities macros The interwebs are plenty of Clojure macro tutorials but I couldn’t find an example of a macro with multiple arities and how one arity could call another. Well, of course I should have had a look at core.clj. When an “else” part is not present if-let just invokes another arity of the macro passing nil for the :else block. The invocation is actually a syntax quote “back tick” that is that the expansion happens in place with the if-let macro invoked with nil, that then expands again into the final macro form.

EuroClojure CFP EuroClojure will be in Krakow this year and the CFP just opened. The process this year will ensure talks proposal gets better over time and is open for collective (and anonymous) feedback. Please take sometime to review the proposed talks, give feedback and help the biggest european Clojure conference getting even better!

Avout: Distributed State in Clojure Avout is a distributed STM implementation. It promises to maintain the same properties of the locally implemented STM on Clojure data structures with the option of crossing boundaries and persist on different “memories” like zookeeper or Mongo. A couple of use cases are provided, such as distributed Atoms (shared memory) or distributed locks. Since I know that the Clojure STM relies heavily on re-tries to enable consistent sequential state, I wonder how this situation is handled if a network is in between. When the transaction is in memory, even with loads of transaction aborts and restarts, the delay is not really noticeable. Plus what happens when I pull the network cable? How Avout knows that the other side was a commit?

Comments (View)
March 11, 2014

Clojure Weekly, March 11th, 2014

Welcome to another issue of Clojure Weekly, my small routine blog contribution to the Clojure sphere! These are just a few links, normally 4/5 urls, pointing at articles, documentation, screencasts, podcasts or anything else that attracts my attention. I add a small comment so you can decide if you want to look at the whole thing or not. That’s it, enjoy!

Clojure at a Newspaper | Pithering About Here’s some shameless self-promotion disguised as a Clojure success story. Jon is reporting back after one year of Clojure production experience at the DailyMail and he is now moving on to a new and exciting Juxt adventure. But great news for me, I just joined the Daily to keep the Clojure tradition alive and kicking (along with the great team here). The fun has just started, read the Weekly (and the Daily) to know more :)

using clojure symbol function to make indirect function call This is the recipe to store “function pointers” in Clojure and use them at some later time. For example: (map #(@(resolve %) 2 2) ‘(+ - =)) maps a collection of functions and applies them to the same operands producing the expected (4 0 true). Once a function is defined and has a name (e.g. with defn) the name of the function is technically a clojure.lang.Symbol that when resolved with resolve returns a clojure.lang.Var Once the var is dereferenced with @ it can finally be invoked with parenthesis.

reborg/jscheme Scheme in Java by Peter Norvig This code repo is the import of the code Peter Norvig released in 1998, a fully working Scheme REPL written in Java. It is decently written and readable and contains all of the main problems you need to face to build a lisp-like language that targets the JVM. Sounds familiar? In looking at the Clojure compiler and runtime these days, I was searching for a lighter implementation of the same problem. Clojure sources aren’t that readable (to me) and I hope that by having a look at how a simpler problem of the same type was solved I can learn the Clojure internal faster.

clojure/src/jvm/clojure/lang/LispReader.java at master · clojure/clojure Welcome to the Clojure Java Lisp compiler. Woah, three languages just to describe it! The LispReader is certainly one of the most important part of Clojure, if not its essence by definition. This class takes a stream (likely from a clojure file) and reads it char by char, tokenising the content and interpreting the token returning a specific Symbol. It is likely the place where most of the Clojure startup time is spent, considering the length of clojure/core.clj. Core.clj is one of the first step of the Clojure initialisation sequence. Before that, a few Symbols are programmatically (and statically) added to the Symbol dictionary so that core.clj top part can be interpreted. The top is defining what needs to be defined for the rest of the file to be parsed and so on.

Idea Hammock - Clojure Design - Clojure Development Yes indeed, Clojure has a wiki to collect ideas. Simple as that. Here you can see for example that people’s WTF? reaction opening Compiler.java is a known fact. Also how to get better error messages has a page and many more, including interesting comments from the Clojure core committers and Rich himself giving directions. Core.async stuff and ClojureScripts ideas are also collected here. Be sure to read carefully what is here before posting your complaints to the mailing list, chances are people already discussed the improvement and what is really needed is some help.

Liberator - Tutorial - All together now I linked liberator a while ago, but as my understanding progresses, I’m making a better job at describing it. Liberator builds on top of Ring and Compojure borrowing from the Erlang WebMachine framework to expose the domain as REST resources. Let me rephrase that in another way. The REST protocol can be represented as a flow chart where nodes are decisions based on request parameters, headers and the URI. Liberator invokes handlers you can optionally provide for each of those decision points finally returning a response. Liberator takes care of many details, including status codes (a valid type of response), caching directives and much more. The page linked here is a comprehensive example of how liberator resources look like.

simple-check contrib - Google Groups The Haskell QuickCheck porting to Clojure is ready to enter the contrib as the new simple-check library. Linked here is the usual process about how to do that: after the reasons why a library should become contrib have been discussed in the mailing list, the authors are invited to give their approval for the license and rights. Following that, the library needs to confirm to the contrib namespace, have a Jenkins build and Jira issue space and that’s it. As of simple-check, it is a very nice addition. With this approach to testing, you need to think about “invariants” of a piece of code and the library will automatically generates tests around those invariants to verify they hold true. Maybe this is not the best approach for all situations but definitely rocks when invariants are clear and edge cases are tricky.

Comments (View)
March 5, 2014

Clojure Weekly, March 5th, 2014

Welcome to another issue of Clojure weekly, my small routinely contribution to the Clojure sphere! I was somehow longer commenting this time, but normally these are just a few links pointing at articles, documentation, screencasts, podcasts or anything else that attracts my attention. That’s it, enjoy!

Episode 3 – FogusFunctional Geekery | Functional Geekery What I like when I learn about the background of the prominent Clojure community figures is that it puts their way to contribute to Clojure, articles, presentations and github projects back into context. It’s the case with Michael Fogus, interviewed by Steven Proctor for the Functional Geekery podcast. He’s got some interesting programming background, starting with logic programming, then Lisp then Scala (to the point of having wright access to the sources), JavaScript and Clojure. Interesting comparison between imperative, functional and logic programming: they are in decreasing order of real-intent to boilerplate ratio. That is that with imperative programming, your real-intent (the pure business logic) is scattered across a larger area. With logic programming, a language based on tree-searching, you tend to express the exact facts and rules of your goal with a very small syntactic waste. I also suggest to follow his 10 paper every programmer must read list. All many more in the show footnotes. Happy listening.

Episode 5 – Colin JonesFunctional Geekery | Functional Geekery Here’s another episode from the Functional Geekery series that I like. A few things I didn’t know about Colin Jones: he’s the creator of Clojure Koans and REPL-y, the REPL I use every time I type lein repl (that is every day). I think the episode gives you an example of a successful path to “Clojure enlightenment” through some of the craftsmanship principles: Colin (who’s not coming from a programming background) used clojure koans as a learning tool as well as providing the rest of the community with a great learning resource. REPL-y is a simple contributions that makes a lot of difference in everyday programming. He did not stop at Clojure: learning other FP languages (like Haskell) will give you part of the background to understand Clojure (Rich Hickey borrowed from Haskell as well as many other interesting languages while designing Clojure). He’s working on another great contribution, co-authoring a book on macros for Pragmatic Press. Overall a pleasant listening with many episodes links to follow right after.

Official Ring Repositories The ring family contains the core (linked here), a few middleware (inside the ring repo) and the Jetty adapter. But it makes much more sense when you also add the lein-ring plugin (for dev) which in turns uses the ring-server (also for dev) which in turns deploys everything on the embedded jetty-adapter. You just want to add Compojure on top, because without routing macros it could end up in a giant mess. The ring middleware modelling of requests and responses is a simple concept. Less simple is to understand how all of the above small pieces collaborate together. The good news is that you don’t need to know (most of the cases). But just in case you are wondering what are we dealing with, I think the Ring family can be described roughly as a Clojure layer on top of the Java Servlet API (and Jetty embedded APIs if you don’t deploy a war) that gets translated into a set of Servlet Filters, Servlet mappings and configuration (programmatic or xml). I think the tendency of describing the Clojure web app approach as a set of isolated small pieces derives mainly from how Ring was laid out in the first place.

jpalardy/vim-slime Here’s what happens when you look around other editors and see what you like and what you don’t. Emacs Cider better integration prompted some searching about how to evaluate code without copy paste into a proper REPL. I’m used to have a tmux pane opened with a lein repl running, so vim-slime seemed a straightforward choice. Now I can ctrl+c+c to send a paragraph for evaluation to the live REPL hosted in tmux or gnu screen.

Code Quarterly - Rich Hickey interview I found this slightly old (2011) but very good in-depth interview on Clojure and its history from Rich The-Man himself interviewed by Michael Fogus. Here you can learn more about Rich learning, thinking and design process. Rich doesn’t not “exercise” on programming, but rather puts a lot into thinking about programming ahead of the keyboard (and time not spent programming is used to read relentlessly books or academic papers). The discussion moves on to language families, Clojure influences and OOP Classes that Rich compares to having to write each chapter of a book using a different language. As of the history part, Rich was big on C++ and then discovered the flexibility of Lisp, in particular that with Lisp he’s able to write only code that matters achieving great degree of focus. With each of the Clojure predecessor (dotLisp, Foil, and Lisplets), Rich experimented with aspects of writing List targeting an hosting VM.

Comments (View)
February 27, 2014

Clojure Weekly, Feb 27th, 2014

Welcome to another issue of Clojure weekly, my small routine blog contribution to the Clojure sphere! These are just a few links, normally 4/5 urls, pointing at articles, documentation, screencasts, podcasts or anything else that attracts my attention. I add a small comment so you can decide if you want to look at the whole thing or not. That’s it, enjoy!

Home | http-kit, high performance HTTP Client/Server for Clojure Ever wondered if Java Servlets (a technology from 1997) are making good use of IO primitives? You need to take that into account when selecting your Clojure web framework. In general, a Java based HTTP server can take two approaches to serve file system resourcest: using the synchronous access or using NIO (aka New IO) a Java standard library introduced with Java 1.4 which makes asynchronous access to external resources. The model is completely different: you need callbacks to receive chunks of bytes whenever they are ready but at least you can re-use the same thread for other work when no chunk are getting processed. HTTP-Kit is a mostly-drop-in replacement for Ring that allows asynchronous processing of resources. The net result is that the amount of HTTP requests that can be served concurrently increase dramatically. No changes for the Ring HTTP protocol handling: a route defines what to invoke and ring middleware can be plugged-in in the chain. It is just the core processing that is changing and is asynchronous and when you do that you’re in danger of the so called callback hell (and not far away from the node.js approach). Read below on how to deal with that.

core.async and Blocking IO This is a nice overview by Marting Trojer about using core.async with different asynchronous IO libraries. The main message is that there is no “core.async” that can help if the operation sent down the channel is a synchronous operation. It will just clog the thread pool core.async is using to deal with requests. Where core.async really shines is where an asynchronous operation (thus requiring some form of callback mechanism) is sent down the pipe. It includes examples with Netty and HTTP-Kit.

Managing Multiple REPLs with Emacs Cider – Screencast | Pithering About Cider is an indispensable add-on for Clojure emacs users. The list of features is impressive (as it is the list of keyboard shortcut you’ll have to learn) and it is very well integrated with Emacs. Integrated means that everything that you’re working on in an editor window can be subject to Cider evaluation and functionalities. In VIM there is something similar but without that level of integration (vim-fireplace calls it a quasi-REPL). In general VIM is less effective embedding outside functionalities in a window pane. In this screencast Jon Pither shows how to work with multiple nREPL connected at the same time.

Episode 1 – Robert C. Martin | Functional Geekery I’m Impressed by the quality of all the episodes of the new Functional Geekery podcast and today I’m reviewing the first of the series. Uncle Bob is the usual entertaining speaker this time talking about the relation between FP and other paradigms. A little review of SICP and teaching programming. FP can be easier to teach when you don’t have to explain that x = x + 1 is perfectly fine in an imperative language (and of course is counter intuitive that x is equal to x + 1, “no is not!”). SICP does a great job at introducing all modern computer science topics at a terrific speed and treating assignment and concurrency as element of “corruption” in the theory. Just to stress that again: REPL driven development is not a replacement for TDD. TDD is like double book-keeping, stating your things twice to make sure you get them right and driving the implementation after stating your goals. FP also gives some more evidence to the Transformation Priority Premise, verifying that in general avoiding assignment and using recursion head toward better implementations. FP tends to insinuate that you need to develop bottom up, so higher abstraction functions can call lower level ones. But with FP you can mock at the function level, something that in OO was unheard of (mock is at the object level), making top-down outside-in approaches pretty possible (see Midje). Many of the SOLID principles still hold true in FP and others are generalizable by looking at the underlining principles. Liskov substitution for example doesn’t work on polymorphism anymore in FP, but it still works at dispatching functions during runtime. A must listen in terms of clarity of explanation of such complicated concepts.

clojure - Why clojurescript macros can’t be written in clojurescript? - Stack Overflow This is the answer if you ever wondered why there is a special require-macros namespace directive in ClojureScript. Essentially, ClojureScript is interpreted by Clojure code, not the reader of the Clojure compiler. This Clojure ClojureScript compiler was not enhanced to deal with macros, task that is delegated to the normal Clojure compiler. For this reason macros needs to be read from Clojure code and expanded in the produced JavaScript.

(shuffle thoughts) — (clojure intrinsics) Again on some Clojure performance tuning. Whenever you search for raw speed and you know your types (and your operations won’t generate overflow) you should never read in you Clojure code the plain operators: +, -, *, / and so on. Those are checked operations that add the additional semantic of throwing an exc on overflow. You should always type hinting when possible, like this article is showing. With the type hint Clojure can select the right function from the list of intrinsics functions avoiding the unnecessary overhead.

Comments (View)
February 19, 2014

Clojure Weekly, Feb 19th, 2014

Welcome to another issue of Clojure weekly, my small routine blog contribution to the Clojure sphere! These are just a few links, normally 4/5 urls, pointing at articles, documentation, screencasts, podcasts or anything else that attracts my attention. I add a small comment so you can decide if you want to look at the whole thing or not. That’s it, enjoy!

Functional Geekery Signalling a new podcasts (5 episodes at the moment) from Steven Proctor (twitter.com/stevenproctor). It’s featuring functional programming in general, but I already see some Clojure dominance :) First guests seem to confirm it: Uncle Bob, Fogus, Colin Jones and other usual suspects from the Clojure community. Looking forward to hear the episodes, you should do it too!

ClojureDocs - clojure.core/declare I rarely had the need for something like this, but it’s useful to remember that also in Clojure (like other multiple-pass languages compilers) you can have forward declarations, that is the possibility to use a symbol before it is defined. Not having this “feature” by default makes it so your code is organised with the low-level functions at the top and the public interface at the bottom of the namespace, which is overall a nice convention. In those rare cases where you need to use forward declare (mocking? double recursion?) declare is there for you. Also a simple def will do, but declare is more explicit in this sense.

[ANN] Clojure 1.6.0-beta1 - Google Groups Clojure 1.6 beta is out for review. No huge changes but general improvements and bug fixing. A feature generating some discussion is another flavour of some? that only checks for nil-ness but has different semantic compared to the already existing “some”. Another noticeable improvement is on hash functions that are now less prone to surprises in case of certain use cases (there was a long and interesting discussion about this in the mailing list).

Scripting Clojure with lein-exec With a shebang on top, optional Pomegranade dependencies and unix pipe support, this lein plugin can be insanely useful. It’s not far away from java -jar clojure.jar of some clojure file after all, but having the specific Clojure version handled by leiningen (including the easy install) it’s a win. An example scenario would be to script the startup of another more complicated Clojure app, preparing files and the system environment. More in general, it is a quick and effective way to do system scripting directly in Clojure.

Comments (View)