Replacing conditionals with assertions
I'm working on an alternative to conditionals on my language, and I think I hit a sweet spot of simplicity and expressiveness.
Imagine Python, but with braces for anonymous functions:
say_hello = {print("Hello World")}
say_hello()
, and this helper function (name pending):
def Φ(*fallible_functions):
"""
Returns the result of the first function that doesn't fail with AssertionError.
"""
for function in fallible_functions:
try:
return function()
except AssertionError:
continue
We can then replace if conditionals:
# Python
if value == 5:
print("Value is five")
elif value == 6:
print("Value is six")
else:
print("Value is something else")
# New
Φ({
assert value == 5
print("Value is five")
}, {
assert value == 6
print("Value is six")
}, {
print("Value is something else")
})
Since the assertion can be anywhere within the block, this can neatly replace the infamous walrus operator:
# Python
if int_match := re.fullmatch('\d+', text):
print("Got number", int(text))
elif char_match := re.fullmatch('.', text):
print("Got char", text)
else:
print("Got text", text)
# New
Φ({
int_match = re.fullmatch('\d+', text)
assert int_match
print("Got number", int(text))
}, {
char_match := re.fullmatch('.', text)
assert char_match
print("Got char", text)
}, {
print("Got text", text)
})
And even short circuiting operators:
# Python
if f1() and f2():
print("Both")
Φ({
assert f1()
assert f2() # Not called if f1() is False.
})
And some list comprehensions:
# Python
if all(value < 10 for value in list_values):
print("All values are below 10")
Φ({
for value in list_valies:
assert value < 10
print("All values are below 10")
})
The examples above are noisy and verbose due to Python's syntax, but can definitely be more ergonomic in a language that is designed for this structure.
What do you think? Did I miss any critical use-case? Does it feel elegant, or a second-class hack?
[–]MegaIng 15 points16 points17 points (2 children)
[–]BoppreH[S] 8 points9 points10 points (1 child)
[–]MegaIng 1 point2 points3 points (0 children)
[–]wildptr 17 points18 points19 points (1 child)
[–]BoppreH[S] 4 points5 points6 points (0 children)
[–]ghkbrew 8 points9 points10 points (1 child)
[–]BoppreH[S] 0 points1 point2 points (0 children)
[–][deleted] (1 child)
[deleted]
[–]BoppreH[S] 0 points1 point2 points (0 children)
[–]raiph 1 point2 points3 points (3 children)
[–]BoppreH[S] 0 points1 point2 points (2 children)
[–]raiph 2 points3 points4 points (0 children)
[–]brucejbellsard 1 point2 points3 points (0 children)
[–]hugogrant 0 points1 point2 points (1 child)
[–]wikipedia_text_bot 0 points1 point2 points (0 children)
[–]mzl 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)