I want to turn a defined function into an anonymous one. How do I do that? The following function returns the last element from a sequence:
(defn lastt [l]
(cond
(nil? (next l)) l
:else
(lastt (next l))))
How do I turn it into fn form?
PS: I know about last function, this is just an exercise.
First of all, that function returns a list with the last item in it. I’d change your definition so that it returns just the last item:
To simplify, I’d use a
letbinding since you’re callingnexttwice onl:The next thing I’d do is replace the final call to
lasttto userecurinsteadAnd then I’d replace that with
And just realised that it could be simplified even more using destructuring 🙂
Updated
No need for the
cond, since there’s only two branches, and usingfninstead of the#shorthand will allow the destructuring to happen in thefn‘s parameters, making the whole function a little bit more concise: