The Life of a Programmer

Leaf: Preserving “lvalue” status

I’ve been reworking how I handle basic type conversion in Leaf. This is a mechanism which allows implicit conversion of simple types. As part of this effort I had to refactor how lvalues work. In brief, an lvalue is simply a value which can be modified by assignment.

I realized that I could now solve an annoying issue of imperative programming. How often do you encounter code that looks like the following?

[sourcecode]
if( cond )
a = some_expr;
else
b = some_expr;
[/sourcecode]

I’ve always hated that repetition of not just ‘some_expr’ but the assignment as well. In leaf I allow lvalues to survive conditionals. A working example:

[sourcecode]
var a : integer;
var b : integer;
(true then b else a) = 17;
trace(b);
[/sourcecode]

Note: you probably won’t need the parens since ‘=’ has a low enough precedence. I’ve just put them there for clarity. Of course you’d have an actual condition rather than just ‘true’.

This works for any conditional statement, though the only other one I have implemented so far is a switch (switches can return values). Its syntax isn’t so pretty yet (I haven’t settled on a good one), but here’s an example.

[sourcecode]
var a : integer;
var b : integer;
var c : integer;
switch {
cond_a then a,
cond_b then b,
else c
} = 17;
[/sourcecode]

C++

In C++ the same thing works using a ternary operator. If both operand types are lvalues then the resulting type is also an lvalue. It doesn’t work in C as-is, but with pointers and some syntax changes you can achieve something similar.

[sourcecode]
//C++ only
int a, b;
(1 ? a : b) = 17;

//C as well
*(1 ? &a : &b) = 17;
[/sourcecode]

Please join me on Discord to discuss, or ping me on Mastadon.

Leaf: Preserving “lvalue” status

A Harmony of People. Code That Runs the World. And the Individual Behind the Keyboard.

Mailing List

Signup to my mailing list to get notified of each article I publish.

Recent Posts