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

Advertisements

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]

(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))))

Leave a ReplyCancel reply