See if some of the data is lazy in clojure

Is there a function in clojure that checks if the data contains some lazy part?

Background:

I am creating a small server in clojure. Each connection has a state, input stream and output stream

The server reads the byte from the input stream and, based on the value, calls one of several functions (with state and input and output stream as parameters). Functions may decide to read more from the input stream, write a response to the output stream, and return a state. This part of the cycle.

This will all work fine if there are no lazy parts in the state. If there is some lazy part in the state that can, when it is evaluated (later, during another function), begin to read from the input stream and write to the output stream.

So basically, I want to add a post-condition to all these functions, stating that no part of the return state can be lazy. Is there a function that checks lazy sequences. I think it would be easy to check whether the state itself is a lazy sequence, but I want, for example, to check whether the state has a vector containing a hash map, one of which is lazy.

+4
source share
2 answers

itโ€™s easier to make sure heโ€™s not lazy by calling a doall

I had this problem in a crypto application to handle a stream several years ago, and I tried several ways until I finally took my lazy side and wrapped the input streams in a lazy sequence that is closed in the input streams when there is no more data It was. effectively separating the care of closing threads from concern about what the threads contained. The state you are tracking sounds a little more complicated than open and closed, although you can separate it in the same way.

+3
source

You could force an assessment using doall , as Arter reasonably suggests.

However, I would recommend refactoring instead to solve the real problem, which is that your handler function has side effects (reading from input, writing to output).

Instead, you can turn this into a pure function if you have done the following:

  • Flow around an input stream as a lazy sequence
  • use [input sequence state] as an input to your handler function.
  • use [list-of-write new-state rest-of-input-sequence] as the output, where the list of records is what should later be written to the output stream.

If you do this, your handler function will be clean, you just need to run it in a simple loop (sending a list of records to the output stream at each iteration) until all the input data is used and / or some other termination condition.

+1
source

Source: https://habr.com/ru/post/1404013/


All Articles