Skip to content

feat: add ternary operator support #37

@mjm918

Description

@mjm918

Description

Add support for ternary conditional expressions to provide concise inline conditionals.

Proposed Syntax

Standard Ternary Operator

var result: int = condition ? value_if_true : value_if_false;

Elvis Operator (truthy-based shorthand)

var result: int = maybe_value ?: default_value;

The Elvis operator ?: returns the left operand if it's truthy, otherwise returns the right operand.

Truthy values: non-zero numbers, non-empty strings, true, some(x)
Falsy values: 0, "", false, none

Note: This differs from ?? (null-coalescing) which only checks for none/null.

Examples

// Standard ternary
var max: int = a > b ? a : b;
var status: string = is_active ? "active" : "inactive";
var sign: string = x >= 0 ? "positive" : "negative";

// Elvis operator (truthy check)
var name: string = user_input ?: "Anonymous";   // "" is falsy
var count: int = cached ?: compute();            // 0 is falsy
var flag: bool = override ?: default_flag;       // false is falsy

// Difference between ?: and ??
var a: option<int> = some(0);
var x: int = a ?: 10;    // Returns 10 (0 is falsy)
var y: int = a ?? 10;    // Returns 0 (some(0) is not none)

Implementation Notes

  • Ternary expressions return a value (unlike if statements)
  • Both branches must have compatible types
  • Elvis operator evaluates truthiness, not just null/none
  • Consider precedence relative to other operators
  • Short-circuit evaluation: right side only evaluated if needed

Related

This addresses the lack of inline conditionals since if is a statement, not an expression in naml.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions