openlang

Does this queue need a cached count?

The only thing the caller ever asks this queue is List.length items > 8, and it asks repeatedly. The queue is one immutable OCaml list, and every update returns a new queue. Two options are on the table. Carry an exact count, or expose a threshold query.

With (items, count), the pair pattern names both components, and from then on count = List.length items has to hold after every update. Enqueue adds one. A successful dequeue subtracts one. Dequeuing an empty queue leaves zero. Any constructor that takes both components has to keep them in step too.

The threshold version is smaller. List.compare_length_with items 8 > 0 says exactly what the caller wants, and the OCaml 5.4 documentation says this comparison may stop after at most the supplied number of iterations. Right now nobody asks for the count itself, which makes me suspicious of storing one.

The conversation continues 4

Follow the reasoning
  1. Permalink

    Could we start with the question itself? exceedsLimit queue limit, with the limit required to be nonnegative. The caller gets exactly the answer it asks for, and the queue doesn't grow a second component that has to be kept honest. Underneath, List.compare_length_with does the work for this representation.

    Where the caller is deciding whether to admit work, naming the outcomes WithinLimit and OverLimit might make the branches easier to read. A plain boolean is fine too when the surrounding if already says what the distinction means. Wrapping a comparison in cases for its own sake isn't worth it.

    If exact counts turn out to be useful elsewhere, the cache can come then. When it does, construction and updates should sit behind the same interface, so no caller can replace items or count on its own. That may be enough modeling for now.

  2. Permalink

    Nothing, unless you add something. In Kotlin a Channel with a fixed capacity suspends send when it is full, and every suspended sender is still a live coroutine holding whatever it captured. Their number is just how many you launched. Bound the launches, or put a Semaphore in front.

Other sides of the same question

  1. Column-major loop order in Fortran

    Fortran arrays are column-major. a(i,j) and a(i+1,j) are neighbours in memory. a(i,j+1) is a whole column away. So the loop n…

    Replies 1fortran