渲染zh-Hans

常量

Translation status: 简体中文 reader-locale proof. Term names and code fences follow the zh-Hans pack; supporting prose may still be English.

Declares an immutable binding.

Aliases: const, immutable

Syntax: 常量 <type|_> <pattern> [← <expression>]

Category#

binding

Examples#

radix/corpus/fixum/fixum.fab (canonical · keyword)#

Declares an immutable binding.

# =============================================================================
# 常量 — Declares an immutable binding
# =============================================================================
#
# What this teaches:
#   • Declares an immutable binding.
#   • Related keywords: 变量, 设, ←
#
# Common mistakes:
#   • Reassigning a `常量` binding after initialization — `常量` is immutable; use `变量` for mutable bindings (SEM020) or defer init with a single later assignment.
#
# See also: 变量, 设, ←
# =============================================================================

# 常量 — immutable bindings
#
# Immediate init:
#   常量 整数 count ← 0
#   常量 _ 名称 ← "Marcus"
#
# Deferred init (write-once): declare without ←, assign exactly once later, then
# freeze. The definite-assignment pass rejects reads before that assignment and
# any second assignment.
#   常量 整数 pending
#   pending ← 42
#
# `设 x` is sugar for `常量 _ x` in both immediate and deferred shapes; see
# 设/sit.fab for the compact inferred spelling.
#
# GRAMMAR:
#   varDecl := ('常量' | '变量') typeAnnotation IDENTIFIER ('←' expression)?
#
# EXPECTED OUTPUT:
#   fixum.expected (Salve, Marcus! / 7 / 30 / 300)

fn scale(bool compact, int base) → int {
    const int factor
    if compact {
        factor ← 10
    }
    else {
        factor ← 100
    }
    return base * factor
}

test "fixum immediate init" {
    const string 名称 ← "Marcus"
    const string salve ← "Salve, §!"(名称)
    assert 名称 ≡ "Marcus"
    assert salve ≡ "Salve, Marcus!"
}

test "fixum deferred init writes once" {
    const int pending
    pending ← 7
    assert pending ≡ 7
}

test "fixum factor selected per branch" {
    assert scale(true, 3) ≡ 30
    assert scale(false, 3) ≡ 300
}

main {
    const string 名称 ← "Marcus"
    const string salve ← "Salve, §!"(名称)
    print salve
    const int pending
    pending ← 7
    print pending
    print scale(true, 3)
    print scale(false, 3)
}

Expected output:

Salve, Marcus!
7
30
300