jsonnet icon indicating copy to clipboard operation
jsonnet copied to clipboard

Implement an Elvis operator

Open nikolay opened this issue 7 years ago • 8 comments
trafficstars

https://en.wikipedia.org/wiki/Elvis_operator

The above is more explicit than generalizing (or abusing, maybe?) the || operator. It's available in languages like Kotlin.

nikolay avatar Feb 28 '18 18:02 nikolay

Jsonnet is lazy. Why wouldn't regular || short circuit?

anguslees avatar Jun 06 '18 21:06 anguslees

It does short circuit, but it does not either

  1. implicitly cast things to bool
  2. In the case that things are not bools, return the original thing instead of "true"

It differs from many scripting languages in this

sparkprime avatar Jun 06 '18 21:06 sparkprime

Ah, that last comment makes it clear to me that this relies on a notion of "truthy", which we don't have in jsonnet. Perhaps a null-coalescing operator (//) would be more clearly defined and useful in json-land (short circuit based on != null), and perhaps meet the original problem statement?

In related news, I note there is no problem statement in this issue :P

anguslees avatar Jun 07 '18 00:06 anguslees

@anguslees The null-coalescing operator // is nice as //= is possible in some languages and ?:= does not make sense.

nikolay avatar Jun 07 '18 01:06 nikolay

Unfortunately // is a comment :)

sparkprime avatar Jun 07 '18 19:06 sparkprime

Unfortunately // is a comment :)

Oh duh :stuck_out_tongue_closed_eyes:

https://en.wikipedia.org/wiki/Null_coalescing_operator has a good survey of the operator in various existing languages. ?? might be a reasonable choice for jsonnet?

However, I say again: I feel like we're iterating a solution that doesn't actually have an associated problem - so we can't actually say if/when we've satisfactorily addressed any original issue.

anguslees avatar Jun 08 '18 06:06 anguslees

I'm not a big fan of writing out thing() != null && thing() >= 123 etc. etc. Much nicer would be thing() ?: 0 >= 123 or even std.coalesce(thing(), 0) >= 123. Does that suffice as a problem statement?

tavin avatar Oct 01 '20 14:10 tavin

You can write your own coalesce function like that, no upstream support required. That said, it would be a valid addition to the stdlib as well.

And maybe coalesce should take an array to allow arbitrary number of values?

sbarzowski avatar Oct 01 '20 16:10 sbarzowski