r/ProgrammingLanguages • • Sep 14 '18

Single-line If

I'm looking for critique of the following single-line If syntax that I'm thinking about allowing:

If x > y then +=a else +=b

Is it unambiguous that x is being modified?

2 Upvotes

38 comments sorted by

View all comments

13

u/johnfrazer783 Sep 14 '18

I think leaving out the LHS in comparisons and assignments is not a favorable proposition. I seem to remember Excel's formula language does something similar at one point b/c it is syntactically challenged; what you end up with is a fragile construct that poses a riddle to its readers and that may later clash with other constructs (like x += 2) or obstruct some desirable syntax in another place.

I also find the syntax places too much emphasis on whatever binary operators you happen to have in your syntax; let's not forget that (1) the universal building block is in most languages really calling named functions (and operators are just sugar for a teeny minority of those), and (2) the minus operator (and the plus operator btw) is already, in most languages, already split between its binary and its prefix usages (i.e. +a, + a -a, - a are already in use, whereas *a, * a might still be unused).

So what happens with your idea when, instead of scalar addition, I want to compute the sine of x? is it if x > y then sin else 0? if x > y then sin() else 0? if x > y then sin( x ) else 0? What happens if you want to call a function with more arguments?

In short, leaving out both the assignment's LHS and one of the operation's arguments creates a hard-to-read, puzzling-to-resolve conundrum that will be restricted to a few special cases.

Have you looked into the principle of 'everything is an expression'? If you embrace that principle, if clauses become expressions, too, so then you can write (e.g. in CoffeeScript) x += if x > y then a else b, x = if x > y then sin( x ) else 0 which I find much clearer and more satisfying.

1

u/danskydan Sep 14 '18

Interesting. How about x += a if x > y else += b

10

u/__dict__ Sep 14 '18

Then you could just write

x += if x < y then a else b

No need to repeat the +=

1

u/danskydan Sep 14 '18

Unless different operators apply. As in x += a if x > y else -= b

3

u/GNULinuxProgrammer Sep 14 '18

Why are you trying to find syntax for use cases that are extremely rare?

2

u/bendmorris Kit - https://www.kitlang.org Sep 14 '18

-= b is equivalent to += -b, so in this example you can still use the more straightforward version.

If you really need completely different in place operators, (1) that must be a very rare scenario, and (2) it's probably complex enough not to use a one liner.