Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a function returning the next list element after it is called in clojure

I have a function (read-line), which asks the user for an input, but i want to write a test, where i determine, what the user uses as input.

I would need a function, that returns 1, when called and 5, when called a second time and so on. Basically, i have a vector of numbers and the next one should be called, when the function is called. How is this possible and what is the clojure way?

vector is [1 5 3]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(myfunction) => 1
(myfunction) => 5
(myfunction) => 3

>Solution :

You can wrap my-function in let with some atom and modify that value.

First option: you’ll create atom with that vector and call first and rest, something like this:

(let [values (atom [1 5 3])]
  (defn my-function []
    (let [e (first @values)]
      (swap! values rest)
      e)))

Second option: you’ll use atom with index and increase that index:

(let [values [1 5 3]
      i (atom -1)]
  (defn my-function []
    (get values (swap! i inc))))

Test for both options:

(my-function)
=> 1

(my-function)
=> 5

(my-function)
=> 3

(my-function)
=> nil

If you want to return to the first element after the third one, you can use cycle or mod:

(let [values (atom (cycle [1 5 3]))]
  (defn my-function []
    (let [e (first @values)]
      (swap! values rest)
      e)))

(let [values [1 5 3]
      i (atom -1)]
  (defn my-function []
    (values (mod (swap! i inc) 3))))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading