« back

Curry - This is Hot Stuff

07 Dec 2012

Need to pass a function that takes more than one argument to a function that only takes a function and one collection or argument? If so, keep reading.

When working with my command parser, I was in a bit of a pickle. I has added encoding options, adding one more argument that I would need to pass to a function and I was using map. Map takes a function, and a collection. Hmmm, well, it turns out that one of the 8th Light craftsmen, Josh Cheek, told me about an idea called currying. It turns out that you can use curried functions as a way to achieve passing multiple arguments. Here goes. So originally, I had...

1 (defn decode-structured-messages [input]
2 	(let [result (map decode-structured-message (split input #";"))]
3 		(doall result)))

When currying, I ended up with this...

1 (defn decode-structured-messages
2 	([input] (decode-structured-message input plain-text))
3 	([input decoder]
4 	(let [result (map (fn [structured-message] (decode-structured-message structured-message decoder )) (split input #";"))]
5 		(doall result))))

You can see that map is taking a function with the argument of structured message. Then decode-structured-message is nested inside with structured message and the decoder being passed to it. The collection, (split input #";"), remains the same.

This is some hot curry!!!!!!! :)

comments powered by Disqus