Recent

Author Topic: functional IF  (Read 3005 times)

Warfley

  • Hero Member
  • *****
  • Posts: 1930
Re: functional IF
« Reply #45 on: June 16, 2025, 12:53:17 pm »
I've been working on something similar for the SharpBASIC compiler, but instead of using IF in an expression, a LET statement is used allowing for one or more 'on' branches:

Code: Text  [Select][+][-]
  1. let s
  2.   on x < y is "Foo";
  3.   on x > y is "Bar" else "Nothing";
  4. end
  5. print(s);

It differs from a case/switch block in that it's purely an assignment statement. This construct clearly separates assignment from boolean evaluation.
This wouldn't work for multiple reasons, first, is is already defined as an operator, meaning it can't be used to follow up on an expression. Especially in this case where it would introduce additional ambiguity:
Code: Pascal  [Select][+][-]
  1. on MyObject = OtherObject is TMyClass
In this case OtherObject is TMyClass is a perfectly normal expression.
Second in Pascal you can't define variables in the code section meaning such a let construct is also not possible.
Lastly the FPC team does not like the introduction of new keywords, which means adding a new keyword for this is also not an option.

Looking at the keywords available, I don't really see a good syntax option here.

Aside from that, if it's only for assignment it's quite limiting, as one of the main usecases for this is using it in function parameters if you don't want to introduce a new variable. If you just do a grep for IfThen in the Lazarus sources, you'll find that around half the use cases of the current IfThen function is not as an assignment.

munair

  • Hero Member
  • *****
  • Posts: 884
  • compiler developer @SharpBASIC
    • SharpBASIC
Re: functional IF
« Reply #46 on: June 16, 2025, 01:54:44 pm »
Second in Pascal you can't define variables in the code section meaning such a let construct is also not possible.

In SharpBASIC definitions are also not allowed in the code section, similar to Pascal, so s must be defined first:

Code: Text  [Select][+][-]
  1. dim s:str;
  2. dim x, y:int;
  3. main do
  4.   let s
  5.     on x < y is "Foo";
  6.     on x > y is "Bar" else "Nothing";
  7.   end
  8.   print(s);
  9. end
  10.  

Like I said, it's an assignment, but I get the idea of having something like this implemented as an intrinsic.
It's only logical.

 

TinyPortal © 2005-2018