This post covers a feature of functions called 'closures'. A closure is a way to associate data permanently with a function.
The first program shows how to bind data to a function.
The second program shows a more complex example of using them.
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 ...
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
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.