Skip to content

By expressions#

Code Example

Runnable Example in Jac and JacLib

# By as an operator

# Simple by expression
glob result = "hello" by "world";

with entry {
    print("Simple by:", result);
}

# Chained by expressions (right-associative)
glob result2 = "a" by "b" by "c";

with entry {
    print("Chained by:", result2);
}

# By with arithmetic expressions
glob result3 = (1 + 2) by (3 * 4);

with entry {
    print("Arithmetic by:", result3);
}

# By in variable assignment
glob x = "input" by "output";

with entry {
    print("Assignment with by:", x);
}
# By as an operator

# Simple by expression
glob result = "hello" by "world";

with entry {
    print("Simple by:", result);
}

# Chained by expressions (right-associative)
glob result2 = "a" by "b" by "c";

with entry {
    print("Chained by:", result2);
}

# By with arithmetic expressions
glob result3 = (1 + 2) by (3 * 4);

with entry {
    print("Arithmetic by:", result3);
}

# By in variable assignment
glob x = "input" by "output";

with entry {
    print("Assignment with by:", x);
}
"""
By as an Operator Example

This example demonstrates the use of 'by' as an operator in various contexts,
including simple usage, chaining, arithmetic expressions, and assignments.
"""

from __future__ import annotations
from jaclang.lib import by_operator

result = by_operator('hello', 'world')
print('Simple by:', result)

result2 = by_operator('a', by_operator('b', 'c'))
print('Chained by:', result2)

result3 = by_operator(1 + 2, 3 * 4)
print('Arithmetic by:', result3)

x = by_operator('input', 'output')
print('Assignment with by:', x)
Jac Grammar Snippet
by_expr: pipe
       | pipe KW_BY by_expr

Description

By as an Operator

The by operator in Jac is a syntactic construct for expression composition. It allows chaining expressions together in a declarative manner.

Note: The exact execution behavior and semantics of the by operator are not yet fully defined. The current implementation focuses on the syntactic structure, and the runtime behavior may evolve in future versions of Jac.

Basic Syntax

The by expression follows the pattern: expression by expression. The operator is right-associative, meaning a by b by c is parsed as a by (b by c).

Simple By Expression

Line 11 demonstrates the basic usage: result = "hello" by "world". This composes the string "hello" with "world" using the by operator.

Chained By Expressions

Line 15 shows chained by operators: result2 = "a" by "b" by "c". Due to right-associativity:

  1. First, "b" by "c" is evaluated
  2. Then, "a" by (result of step 1) is evaluated

By with Arithmetic

Line 19 demonstrates by with arithmetic expressions: result3 = (1 + 2) by (3 * 4). The parentheses ensure the arithmetic operations are evaluated before the by composition.

Common Use Cases

The by operator is commonly used with:

  • LLM function calls: def process(input: str) -> str by llm()
  • Function composition patterns
  • Data transformation pipelines