google / jsonnet

Jsonnet - The data templating language
http://jsonnet.org
Apache License 2.0
6.98k stars 440 forks source link

Implement an Elvis operator #468

Open nikolay opened 6 years ago

nikolay commented 6 years ago

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.

anguslees commented 6 years ago

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

sparkprime commented 6 years ago

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

anguslees commented 6 years ago

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

nikolay commented 6 years ago

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

sparkprime commented 6 years ago

Unfortunately // is a comment :)

anguslees commented 6 years ago

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.

tavin commented 4 years ago

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?

sbarzowski commented 4 years ago

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?