squiggle icon indicating copy to clipboard operation
squiggle copied to clipboard

Early return operator

Open berekuk opened this issue 11 months ago • 0 comments

Discussed here: https://eaforecasting.slack.com/archives/C030T49UHSS/p1737486831253379

Long nested ifs in FP can get ugly. I wonder if we could add some syntax for early returns, and keep the rest of Squiggle functional.

  agentFieldDistribution(agent, property) = {
    propertyValues = data[property]
    if typeOf(propertyValues) == "Dictionary" then {
      values = propertyValues[agent]
      if typeOf(values) == "Dictionary" then {
        propertyDistribution(values, property)
      } else "undefined"
    } else "undefined"
  }

->

  agentFieldDistribution(agent, property) = {
    propertyValues = data[property]    
    returnif typeOf(propertyValues) != "Dictionary" then "undefined"

    values = propertyValues[agent]
    returnif typeOf(values) != "Dictionary" then "undefined"

    propertyDistribution(values, property)
  }

One downside, as we discussed, is that this feature is pretty unique, i.e. I can't find any FP languages that have this.

On returnif [condition] then [expression]:

  • new keyword at the beginning is convenient for parsing. if ... then return ... would be more complicated, because the entire construct is not an expression, but a statement
  • the specific keywords could be different; maybe return [expression] if [condition]? (I think I prefer the condition -> expression order though)

berekuk avatar Jan 21 '25 20:01 berekuk