What do you think about adding `back` function in Queue module?

While translating some tools written in Python into OCaml, I found that the OCaml standard library itself could become more improved in some way.
One example is the module Queue. It has such a simple and powerful implementation, but it lacks the functionality of back (just like c++'s std::vector::back). I think adding functions like the below could improve this module’s usability hugely.

let back q =
  match q.last with 
  | Nil -> raise Empty
  | Cons { content } -> content

let back_opt q =
  match q.last with 
  | Nil -> None
  | Cons { content } -> Some content

I wonder why this function is missing from stdlib in the first place, and I hope if I can make a contribution related to it.

Judging by your code snippet, I think you have confused the module Queue with Seq. For Seq, discussion is ongoing to add more functions to the stdlib (including “tail”), see https://github.com/ocaml/ocaml/pull/10583.


Thanks for your comment.

After I’ve read the Seq's tail implementation, I found I’ve confused the name of the tail function. back or last is more suitable for my original intention, similar to the c++'s std::vector::back which returns the last element of the container. (I’ve updated the title and the content)
The current Queue module implementation makes it trivial to add this feature, so I thought it would be nice to get better usability.

OCaml’s Queue module is intended as a (single-ended) queue (you write at one end and read at the other end), not a (double-ended) dequeue (you can read and write at both ends). The back function you propose is a dequeue function. This said, this function makes sense, and is trivial to add, so maybe we should consider adding it and other dequeue operations to the Queue module.


Thanks for your comment.
If this proposal about adding double-ended queue features does make sense, and it is ok for me to contribute to it, then I want to make a pull request for this!

1 Like