Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

let vs letfn for defining local functions in clojure?

Tags:

clojure

When in practice should I use letfn vs. let for defining local functions? What about cases where I want both local functions and local non-functions?

like image 793
Arthur Ulfeldt Avatar asked Jul 29 '09 00:07

Arthur Ulfeldt


2 Answers

If all I need is one or a few local functions, I letfn them. If I need to define a mix of functions and non-functions, I'll just use a normal let. letfning and leting would be a very verbose way to do this.

However, if you need mutual recursion through your local functions, you'll have to letfn them either way.

Short version: use them when you think it looks better, and when it's convenient. There are no hard and fast rules for using either. They are just tools in the Clojure toolbox.

Have fun!

like image 137
Rayne Avatar answered Sep 23 '22 18:09

Rayne


Normally it's easier and neater to use let: that way you can define a set of both functions and non-functions in a single form, and even refer back to previous definitions:

(let [f     (fn [x] ....)       value (reduce f some-collection)       foo   bar]   .....) 

letfn is really only needed when you want to define multiple functions that recursively refer to each other. let won't work in this case because it doesn't support recursive references.

like image 45
mikera Avatar answered Sep 23 '22 18:09

mikera