Choosing one of two numbers based on a condition
You already know to use the list selection [x,y][b] with a Boolean b for the ternary expression y if b else x. The variables x, y, and b can also be expressions, though note that both x and y are always evaluated unlike in the ternaryeven when not selected.
Here's some potential optimizations when x and y are numbers.
- x=0 Use
[0,y][b] -> y*b - x=1: Use
[1,y][b] -> y**b - y=1: Use
[x,1][b] -> b or x - y=x+1 (or y=x-1): Use
[x,x+1][b] -> x+b(or [x,x-1][b] -> x-b)- General explicit numbers x,y: Use
[1,-1][b] -> 1|-b [x,~x][b] -> x^-b[x,y][b] -> x+z*bor(ory-z*b), where z=y-x.
You can also switch x and y if you can rewrite b to be its negation instead.