DEV Community

Cover image for Programming in Clojure (Part 3 Closures)
Mark Mahoney
Mark Mahoney

Posted on • Edited on

4 1

Programming in Clojure (Part 3 Closures)

This post covers a feature of functions called 'closures'. A closure is a way to associate data permanently with a function.

Closures

The first program shows how to bind data to a function.

The second program shows a more complex example of using them.

Call to Action

Problem 1
Write a function that returns a function. The Fibonacci numbers are a sequence of numbers that are generated by summing the previous two numbers together:

0 1 1 2 3 5 8 13 21 34 ...
Enter fullscreen mode Exit fullscreen mode

Usually, the first two numbers are assumed to be 0 and 1. The returned function should use the specified first numbers in the sequence and print out all of the numbers up to the passed in one.

(defn fibs-fn[firstFib secondFib] ...) ;;fill this in

(def another-fib (fibs-fn 10 15))
(another-fib 5) ;;print first 5 fibs: 10 15 25 40 65
Enter fullscreen mode Exit fullscreen mode

Comments and Feedback

You can find all of these code playbacks in my free 'book', An Animated Introduction to Clojure. I am always looking for feedback so please feel free to comment here or to send me a message. You can follow me on twitter @markm208.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay