[Pitch] Replace the ternary operator with an in-language function


(Jon Hull) #1

-1 to replacing this with the functions mentioned.

At some point, I would like to see an operator which lifts a value into an optional based on a boolean value (basically the opposite of ??). That is it is either the value or nil based on some boolean value. If we use ‘?’ as a binary operator which does this:

  let optional = boolVal ? value //optional is value if boolVal is true, otherwise it is nil

…then the behavior of the Ternary operator behavior falls out without special casing in the compiler (using ‘??' instead of ‘:’):

  let answer = boolVal ? “true” ?? “false"

It also allows you to chain ‘else if’ style statements together ad infinum:

  let answer = (x ? “one”) ?? ( y ? “two”) ?? “three”

That may be too many question marks (as you can see I had to use parenthesis to clarify for myself), so we might want to choose some other similarly terse symbol. I think the core idea is sound though. I have used it in many DSLs (with different syntax: ‘?(bool) “true" | “false"') and it was enormously helpful/flexible.

Not sure what the best syntax would be (just throwing out ideas). Maybe something like:
  
  let optional = value.?(boolVal)
  
  let answer = “one”.?(x) ?? “two.?(y) ?? “three"

Even with it though, I would still favor a two-stage replacement, depreciating it for a while before removing it. They could co-exist for as long as needed, until it makes sense to simplify the compiler by removing the ternary operator.

Honestly, I would really like to go the other way, adding some sort of terse operator which is to switch what the ternary operator is to if. This would basically have the semantics similar to a dictionary, but being an operation. Horrible throwaway syntax to get the basic point across:

  let answer = value ?{ .small: 5, .medium: 10, .large: 20} //Answer is 5, 10, or 20 depending upon the value in value

The compiler would force completeness the same way it does with switch.

Thanks,
Jon