Functions
Functions in legionhjyu are defined with blade. They're first-class values — you can pass them around, return them, and store them in variables.
Basic function
lhj
blade add(a: int, b: int) -> int:
release a + b
echo add(3, 4) ## 7release returns a value. A function with no release statement returns zilch.
Default parameters
lhj
blade greet(name: str, greeting: str = "Hello") -> str:
release "{greeting}, {name}!"
echo greet("Aria") ## Hello, Aria!
echo greet("Rex", "Salutations") ## Salutations, Rex!Keyword arguments
lhj
blade info(name, hp = 100, level = 1):
echo "{name} | HP: {hp} | Level: {level}"
info("Aria", level=5) ## Aria | HP: 100 | Level: 5
info("Rex", hp=50, level=3) ## Rex | HP: 50 | Level: 3Return type hints
lhj
blade square(n: int) -> int:
release n * n
blade name_of(x) -> str:
release str(x)Return hints are optional and not enforced at runtime.
Closures
lhj
blade make_counter(start: int = 0):
forge count = start
blade increment():
count <- count + 1
release count
release increment
forge counter = make_counter(10)
echo counter() ## 11
echo counter() ## 12
echo counter() ## 13The inner increment captures count from the outer scope.
Lambda — lam
lam creates an anonymous function:
lhj
forge double = lam x: x * 2
echo double(5) ## 10
forge add = lam a, b: a + b
echo add(3, 4) ## 7Lambdas take a parameter list and a single expression body.
Pipeline operator |>
lhj
forge nums = [5, 3, 1, 4, 2]
forge result = nums |> sorted |> reversed
echo result ## [5, 4, 3, 2, 1]|> passes the left side as the first argument to the right side. Useful for chaining:
lhj
forge n = 16
|> float
|> math.sqrt
echo n ## 4.0Variadic arguments
lhj
blade sum_all(...nums):
forge total = 0
march n in nums:
total <- total + n
release total
echo sum_all(1, 2, 3, 4, 5) ## 15Decorators
lhj
blade timer(fn):
blade wrapper(...args):
forge start = os.time()
forge result = fn(...args)
forge elapsed = os.time() - start
echo "Took {elapsed}s"
release result
release wrapper
@timer
blade slow_fn(n):
march i in 1..n:
## work...
skip
release n
slow_fn(1000)Decorators wrap a function at definition time. The @timer line above is equivalent to slow_fn = timer(slow_fn).
Recursive functions
lhj
blade factorial(n: int) -> int:
blade n <= 1: release 1
release n * factorial(n - 1)
echo factorial(10) ## 3628800Higher-order functions
lhj
forge nums = [1, 2, 3, 4, 5, 6]
## filter: keeps items where fn returns truthy
forge evens = filter(lam x: x % 2 == 0, nums)
## map: applies fn to each item
forge doubled = map(lam x: x * 2, nums)
## reduce: folds with fn
forge total = reduce(lam acc, x: acc + x, nums, 0)
echo evens ## [2, 4, 6]
echo doubled ## [2, 4, 6, 8, 10, 12]
echo total ## 21