HP 的语法设计遵循「零运行时」原则:能编译期确定的事绝不推迟到运行时。下文按主题组织,覆盖从数据类型到编译期执行的全部能力。HP's grammar follows the zero-runtime principle. Topics below span from data types to compile-time execution.
HP 区分定长数值、便捷类型与复合容器。所有容器均为同构(异构请用 enum/struct)。HP separates fixed-width numbers, convenience aliases and composite containers. Containers are homogeneous.
a = 10 # 自动推断为 int (底层 i64)
b = 3.14 # 自动推断为 float (底层 f64)
c: i32 = 42 # 显式定长类型
name = "HP" # str: 不可变切片 (ptr, len)
xs: list[i32] = [1, 2, 3]
s: set[i32] = {1, 2, 3}
t = (1, "a", true)
person = {"name": "Alice", "age": 25} # json 字面量算术、比较、逻辑、位运算、集合、成员、身份、复合赋值一应俱全;字符串/列表/元组支持拼接与重复。Arithmetic, comparison, logical, bitwise, set, membership, identity and compound-assignment operators are all present.
x = 10 + 3 * 2 # 16
y = 7 % 3 # 1
z = 2 ** 8 # 256
b = (x > 5) and (y < 2)
bits = 0b1100 | 0b0011 # 0b1111
text = "ab" * 3 # "ababab"
lst = [1, 2] + [3] # [1, 2, 3]
ok = 3 in xs
same = a is b # 仅对 ptr/ref/可变容器有效count = 0 # 变量
const PI = 3.14159 # 常量(编译期)
a, b = 1, 2 # 多变量赋值
head, *tail = [1,2,3,4] # 解包:head=1, tail=[2,3,4]
x, y, z = (10, 20, 30)支持 if/elif/else、for/while、break/continue、循环 else 子句、pass,缩进或 {} 皆可界定代码块。if/elif/else, for/while, break/continue, loop-else and pass — blocks via indentation or braces.
if score >= 90:
grade = "A"
elif score >= 60:
grade = "B"
else:
grade = "C"
for i in 0..10:
print(i)
for item in xs:
if item == 0: continue
if item == 9: break
while running:
tick()
# 遍历带索引
for idx, val in enumerate(xs):
print(idx, val)支持默认参数、可变参数、*args、重载、匿名函数(闭包)、文档字符串与递归。Default args, variadics, *args, overloading, lambdas (closures), docstrings and recursion.
fn add(a: int, b: int = 1) -> int {
return a + b
}
# 匿名函数 / 闭包
square = fn(x) { return x * x }
nums = map(xs, fn(x) { return x * 2 })
# 递归
fn fib(n: int) -> int {
if n <= 1 { return n }
return fib(n - 1) + fib(n - 2)
}
# 函数重载(按参数数量分派)
fn show(x: int) { print("int", x) }
fn show(x: str) { print("str", x) }struct Point {
x: num
y: num
}
enum Color { Red, Green, Blue }
interface Printable {
fn print(self)
}
impl Printable for Point {
fn print(self) { print("(", self.x, ",", self.y, ")") }
}
p = Point { x: 3, y: 4 }
p.print()列表 / 字典 / 集合推导式在编译期展开为高效循环。List / dict / set comprehensions expand to efficient loops at compile time.
squares = [x * x for x in 0..10] # [0,1,4,...81]
evens = [x for x in xs if x % 2 == 0]
mapped = {str(x): x for x in 0..5} # json
uniq = {x for x in xs} # setmatch 支持枚举、字面量、守卫、通配;switch 针对整数/枚举生成跳转表,支持范围匹配。match supports enums, literals, guards and wildcards; switch builds jump tables with range matching.
name = match color {
Color::Red => "红色"
Color::Green => "绿色"
Color::Blue => "蓝色"
_ => "未知"
}
switch (score) {
case 90..=100: print("优秀")
case 80..89: print("良好")
case 0..59: print("不及格")
default: print("无效")
}result = [1, 2, 3, 4, 5]
|> map(fn(x) { return x * 2 })
|> filter(fn(x) { return x > 5 })
# 等价于 filter(map(...)) —— 数据从左向右流动赋值默认转移所有权;堆类型必须显式 move,& 创建不可变/可变借用,NLL 检查在编译期完成。Assignment transfers ownership; heap types require explicit move; & borrows; NLL checking at compile time.
a = [1, 2, 3]
b = move a # 显式转移,a 失效
r = &b # 不可变借用
fn read(data: &list[num]) { print(data.len()) }macro debug_print(msg) {
print("DEBUG: " + msg)
}
const fn factorial(n: i32) -> i32 {
if n <= 1 { 1 } else { n * factorial(n - 1) }
}
const FACT_10 = factorial(10) # 编译期算出 3628800
@compileExec
fn gen_table() -> [f64; 8] {
t: [f64; 8]
for i in 0..8: t[i] = f64(i)
return t
}用 #[attr] 控制内联、目标指令集、分支预测、内存布局与向量化。Use #[attr] to control inlining, target ISA, branch hints, layout and vectorization.
#[inline(always)] fn hot() { ... }
#[cold] fn handle_error(e) { ... }
#[target_feature("+avx2")] fn dot(a, b) { ... }
#[likely] if x > 0 { ... } else #[unlikely] { ... }
#[repr(C)] struct Cfg { a: i32, b: i32 }Result[T, E] 利用 niche 优化实现零额外空间,? 运算符零成本传播错误。Result[T, E] is niche-optimized to zero extra space; ? propagates errors at zero cost.
fn might_fail(x: int) -> Result<int, str> {
if x > 0 { return Ok(x) }
return Err("negative")
}
fn use_it() {
val = might_fail(10)? # 自动解包,Err 则提前返回
print(val)
}