jq icon indicating copy to clipboard operation
jq copied to clipboard

Add head and tail builtins

Open reegnz opened this issue 2 years ago • 5 comments

head:

  • returns a single value or empty if input is a list
  • returns a string or empty if input is a string
  • fails if input is neither list or string

tail:

  • returns a list if input is a list
  • returns a string if input is a string
  • fails if input is neither list or string

reegnz avatar Sep 07 '23 16:09 reegnz

These primitives helped me in implementing some convenience functions on top of them: https://github.com/reegnz/dotfiles/tree/master/jq

Most notably converting to/from camelcase.

Capitalizing strings is also easier to implement with such primitive filters exposed by jq.

reegnz avatar Sep 07 '23 16:09 reegnz

Alternatively, one could use these as heads and tails (more cryptic, but gets the job done:

For lists:

[ .[:1][], .[1:]]

For strings:

[.[:1], .[1:]]

The unwrapped head for lists is inspired by other languages usually called destructuring, eg.: https://elixir-lang.org/getting-started/pattern-matching.html https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment https://www.typescriptlang.org/docs/handbook/variable-declarations.html#destructuring

reegnz avatar Sep 07 '23 17:09 reegnz

Sorry to be so negative, but I don't see the point of these additions, and indeed based on my present understanding, they seem to just add bloat at best and confusion at worst (confusion, because of the history of car and cdr; see also @jadutter's remarks).

Perhaps I'm missing something? Please feel free to enlighten me :-)

pkoppstein avatar May 31 '24 18:05 pkoppstein

I don't mind the specific terminology used. Can be head and tail, or first and rest or even firstItem vs remainingItems (although this one would diverge most from existing naming in other languages).

Calling it bloat sounds funny to me. It's true, most functional languages are complex because they have stdlib-s with higher order abstractions shipping with them. Wouldn't call that bloat though, that's a pretty big stretch.

Just please give this the benefit of the doubt instead of straight up calling it bloat and dismissing it. People do make use of taking the first item and remaining items of a list.

An alternative to filters is to make destructuring a language-level feature, like in javascript and clojure.

reegnz avatar Jun 03 '24 12:06 reegnz

BTW original issue I've opened was #2260 this was just a quick run at the problem, I don't mind how it's solved.

reegnz avatar Jun 03 '24 12:06 reegnz