Meaning of "alt!" in Clojure - clojure

in clojure.core.async there is a function named alts! to wait for a message on multiple channels. In Go this is called select (like select a message from multiple channels), but what is the meaning of "alt" in Clojure?
I know what the function does, but it is hard for me to remember the function name when I do not know what "alts" means? Is it a shortcut for "alternative(s)"?

From the docstring for alt! (emphasis added):
Makes a single choice between one of several channel operations,
as if by alts!
and for alts! (emphasis added):
Completes at most one of several channel operations.
This would support the idea that "alt" is short for "alternative" or "alternatives". In other words, make a choice of one of several alternatives.

Related

What does completing function do in Clojure?

I've came across completing function on clojuredocs but there is no doc at the moment.
Could you provide some examples?
completing is used to augment a binary reducing function that may not have a unary overload with a unary "completion" arity.
The official transducers reference page hosted # clojure.org explains the purpose of the nullary, unary and binary overloads of transducing functions and includes a good example of when the unary "completion" arity is useful in the section called "Creating Transducers" (the example used is partition-all which uses completion to produce the final block of output).
In short, the completion arity is used after all input is consumed and gives the transducing function the opportunity to perform any work to flush any buffers that the transducing process might maintain (as in the case of partition-all), apply any final transformations to the output (see below for an example of that) etc. Here by "transducing function" I mean the transducing function actually passed to transduce (or eduction or any similar function that sets up a transducing process) together with all the wrapping transducers.
For an interesting example of completing used with a non-trivial completion function, have a look at Christophe Grand's xforms: net.cgrand.xforms.rfs/str is a transduce-friendly version of clojure.core/str that will build up a string in linear time when used in a transduce call. (In contrast, clojure.core/str, if used in reduce/transduce, would create a new string at each step, and consequently run in O(n²) time.1) It uses completing to convert the StringBuilder that it uses under to hood to a string once it consumes all input. Here's a stable link to its definition as of the current tip of the master branch.
1 Note, however, that clojure.core/str runs in linear time if used with apply – it uses a StringBuilder under the hood just like net.cgrand.xforms.rfs/str. It's still convenient from time to time to have a transduce-friendly version (for use with transducers, or in higher-order contexts, or possibly for performance reasons when dealing with a large collection that can be reduced be efficiently than via first/next looping that str uses).

In Clojure (core.async) what's the difference between alts and alt?

I can't figure out the difference between:
alts!
and
alt!
in Clojure's core.async.
alts! is a function that accepts a vector of channels to take from and/or channels with values to be put on them (in the form of doubleton vectors: [c v]). The vector may be dynamically constructed; the code calling alts! may not know how many channels it'll be choosing among (and indeed that number need not be constant across invocations).
alt! is a convenience macro which basically acts as a cross between cond and alts!. Here the number of "ports" (channels or channel+value pairs) must be known statically, but in practice this is quite often the case and the cond-like syntax is very clear.
alt! expands to a somewhat elaborate expression using alts!; apart from the syntactic convenience, it offers no extra functionality.

See if part of data is lazy in clojure

Is there a function in clojure that checks whether data contains some lazy part?
Background:
I'm building a small server in clojure. Each connection has a state, an input-stream and an output-stream
The server reads a byte from an input-stream, and based on the value calls one of several functions (with the state and the input and output stream as parameters). The functions can decide to read more from the input-stream, write a reply to the output stream, and return a state. This part loops.
This will all work fine, as long as the state doesn't contain any lazy parts. If there is some lazy part in the state, that may, when it gets evaluated (later, during another function), start reading from the input-stream and writing to the output-stream.
So basically I want to add a post-condition to all of these functions, stating that no part of the returned state may be lazy. Is there any function that checks for lazy sequences. I think it would be easy to check whether the state itself is a lazy sequence, but I want to check for instance whether the state has a vector that contains a hash-map, one of whose values is lazy.
it's easier to ensure that it is not lazy by forcing evaluation with doall
I had this problem in a stream processing crypto app a couple years back and tried several ways until I finally accepted my lazy side and wrapped the input streams in a lazy sequence that closed in input streams when no more data was available. effectively separating concern for closing the streams from the concern over what the streams contained. The state you are tracking sounds a little more sophisticated than open vs closed though you may be able to separate it in a similar manner.
You could certainly force evaluation with doall as Arther wisely suggests.
However I would recommend instead refactoring to solve the real problem, which is that your handler function has side effects (reading from input, writing to output).
You could instead turn this into a pure function if you did the following:
Wrap the input stream as a lazy sequence
use [input-sequence state] as input to your handler function
use [list-of-writes new-state rest-of-input-sequence] as output, where list of writes is whatever needs to be subsequently written to the output stream
If you do this, your handler function is pure, you just need to run it in a simple loop (sending the list-of-writes to the output stream on each iteration) until all input is consumed and/or some other termination condition is reached.

Data format safety in clojure

Coming from a Java background, I'm quite fond of static type safety and wonder how clojure programmers deal with the problem of data format definitions (perhaps not just types but general invariants, because types are just a special case of that.)
This is similar to an existing question "Type Safety in Clojure", but that one focuses more on the aspect of how to check types at compile time, while I'm more interested in how the problem is pragmatically addressed.
As a practical example I'm considering an editor application which handles a particular document format. Each document consists of elements that come in several different varieties (graphics elements, font elements etc.) There would be editors for the different element types, and also of course functions to transform a document from/to a byte stream in its native on-disk format.
The basic problem I am interested in is that the editors and the read/write functions have to agree on a common data format. In Java, I would model the document's data as an object graph, e.g. with one class representing a document and one class for each element variety. This way, I get a compile-time guarantee about what the structure of my data looks like, and that the field "width" of a graphics element is an integer and not a float. It does not guarantee that width is positive - but using a getter/setter interface would allow the corresponding class to add invariant guarantees like that.
Being able to rely on this makes the code dealing with this data simpler, and format violations can be caught at compile-time or early at runtime (where some code attempts to modify data that would violate invariants).
How can you achieve a similar "data format reliability" in Clojure? As far as I know, there is no way to perform compile-time checking and hiding domain data behind a function interface seems to be discouraged as non-idiomatic (or maybe I misunderstand?), so what do Clojure developers do to feel safe about the format of data handed into their functions? How do you get your code to error out as quickly as possible, and not after the user edited for 20 more minutes and tries to save to disk, when the save function notices that there is a graphics element in the list of fonts due to an editor bug?
Please note that I'm interested in Clojure and learning, but didn't write any actual software with it yet, so it's possible that I'm just confused and the answer is very simple - if so, sorry for wasting your time :).
I don't see anything wrong or unidiomatic about using a validating API to construct and manipulate your data as in the following.
(defn text-box [text height width]
{:pre [(string? text) (integer? height) (integer? width)]}
{:type 'text-box :text text :height height :width width})
(defn colorize [thing color]
{:pre [(valid-color? color)]}
(assoc thing :color color))
... (colorize (text-box "Hi!" 20 30) :green) ...
In addition, references (vars, refs, atoms, agents) can have an associated validator function that can be used to ensure a valid state at all times.
Good question - I also find that moving from a statically typed language to a dynamic one requires a bit more care about type safety. Fortunately TDD techniques help a huge amount here.
I typically write a "validate" function which checks all your assumptions about the data structure. I often do this in Java too for invariant assumptions, but in Clojure it's more important because you need to check thinks like types as well.
You can then use the validate function in several ways:
As a quick check at the REPL: (validate foo)
In unit tests: (is (validate (new-foo-from-template a b c)))
As a run-time check for key functions, e.g. checking that (read-foo some-foo-input-stream) is valid
If you have a complex data structure which is a tree of multiple different component types, you can write a validate function for each component type and have the validate function for the whole document call validate for each sub-component recursively. A nice trick is to use either protocols or multimethods to make the validate function polymorphic for each component type.

Defining Idempotence

So "idempotence" can be defined as:
An action, that if performed N times has the same effect as performing the action only once.
Got it, easy enough.
My question is about the subtlety of this definition -is an action considered idempotent by itself, or must you also consider the data being passed into the action?
Let me clarify with an example:
Suppose I have a PUT method that updates some resource, we'll call it f(x)
Obviously, f(3) is idempotent, as long as I supply 3 as the input. And equally obvious, f(5) will change the value of the resource (i.e., it will no longer be 3 or whatever value was there previously)
So when we talk about idempotence, are we referring to the generalization of the action/function like (i.e., f(x)), or are we referring to action/function + the data being passed into it (i.e., f(3))?
Suppose I have a PUT method that updates some resource, we'll call it
f(x)
Obviously, f(3) is idempotent, as long as I supply 3 as the input. And
equally obvious, f(5) will change the value of the resource (i.e., it
will no longer be 3 or whatever value was there previously).
This is only obvious is the server implementation is such that PUT respects this idempotent property. In the context of HTTP, RFC 2616 says:
Methods can also have the property of "idempotence" in that (aside
from error or expiration issues) the side-effects of N > 0 identical
requests is the same as for a single request.
Going a bit off topic...
In a distributed system like the web, you may also want to consider commutativity and concurrent requests. For example N+1 of the same PUT(x1) request should have the same effect, but you don't know if another client made a different PUT(x2) request in between yours, so while nPUT(x1)=PUT(x1) and mPUT(x2)=PUT(x2), the two sets of requests could be interleaved.
Idempotence requires that the action holds for all values over its domain, i.e., f(f(x)) = f(x) for all x. Another way to think about it is that an operation is idempotent if the composition of the operation with itself is just that operation.
You're assuming idempotence means that the state of the server will be changed at most once by a series of invocations. Most of the time, people use this term to mean that the state on the server won't be changed at all by any number of invocations. Under these circumstances, the distinction between your two cases is immaterial.
This is not quite the definition of idempotence. A function is idempotent if for any item x, f(f(x)) == f(x).
PUT is a side effect of your f() function here, not the result of it.