EXAMPLE CORPUS

HP 示例库HP Examples

真实可编译的 .hp 片段,覆盖语言的主要能力。点击「复制」或「下载 .hp」即可拿到本地用 hpc 编译运行。Real, compilable .hp snippets covering the language's main capabilities. Copy or download .hp to build locally with hpc.

hellomodule

Hello HP

程序入口、模块导入与基础算术。Entry point, module import and basic arithmetic.

helloworld.hp
module {
    "<std.io>"
}

fn main() {
    a: int = 1
    b: int = 2
    c: int = a + b
    std.io.print("Hello HP!", c)
}
features运算符

运算符全家桶

算术、位运算、比较、逻辑与复合赋值。Arithmetic, bitwise, comparison, logical and compound assignment.

test_features.hp
fn main() {
    a = 10
    b = a + 5
    p, q = 60, 13
    r = p & q       # 12
    r = p | q       # 61
    r = p ^ q       # 49
    r = p << 2      # 240
    n = 100
    n += 5          # 105
    print(10 > 5)   # true
    print(true and false)  # false
}
struct字段

结构体 Struct

值语义结构体与字段访问。Value-semantics struct with field access.

_t_struct.hp
struct Point {
    x: num
    y: num
}

fn main() {
    p = Point { x: 10, y: 20 }
    print(p.x)
    q = Point { x: 1, y: 2 }
    print(p.x + q.y)
}
enummatch

枚举与模式匹配

标签联合 + match 解构为字面量。Tagged union + match destructured to literals.

_t_enum.hp
enum Color { Red, Green, Blue }

fn main() {
    c = Color::Red
    name = match c {
        Color::Red   => "红色"
        Color::Green => "绿色"
        Color::Blue  => "蓝色"
    }
    print(name)
}
match通配

match 通配符

语句级 match 与 _ 默认臂。Statement-level match with the _ wildcard arm.

_t_match.hp
enum Color { Red, Green, Blue }

fn main() {
    c = Color::Green
    match c {
        Color::Red   => print(10)
        Color::Green => print(20)
        Color::Blue  => print(30)
    }
    n = 7
    desc = match n {
        1 => "一"
        2 => "二"
        _ => "其他"
    }
    print(desc)
}
switch范围

switch 范围匹配

整数范围、多值、左开/右开区间与 default。Integer ranges, multi-value, open/closed intervals and default.

_t_switch.hp
fn report(score: i32) {
    switch (score) {
        case 90..=100: print("优秀")
        case 80..89:   print("良好")
        case 60..69:   print("及格")
        case 0..59:    print("不及格")
        default:       print("无效分数")
    }
}

fn bucket(x: i32) {
    switch (x) {
        case ..0:  print("负")
        case 0..10: print("小")
        case 10..: print("大")
    }
}
interfaceimpl

接口与实现

trait 式接口 + impl 方法分派。Trait-style interface + impl method dispatch.

_t_interface.hp
interface Printable {
    fn print(self)
}

struct Document { title: str }

impl Printable for Document {
    fn print(self) {
        print("文档: " + self.title)
    }
}

fn main() {
    doc = Document { title: "HP 设计" }
    doc.print()
}
impl方法

结构体方法

为结构体附加方法与关联函数。Attach methods and associated functions to a struct.

_t_impl.hp
struct Point { x: num; y: num }

impl Point {
    fn add(self, other: Point) -> num {
        return self.x + other.x + self.y + other.y
    }
    fn make() -> Point {
        return Point { x: 1, y: 2 }
    }
}

fn main() {
    p = Point { x: 3, y: 4 }
    q = Point::make()
    print(p.add(q))
}
macro编译期

宏 Macro

编译期展开,不生成运行时代码。Expands at compile time, emits no runtime code.

_t_macro.hp
macro debug_print(msg) {
    print("DEBUG: " + msg)
}

fn test_macro() {
    debug_print("hello")
}

fn main() {
    test_macro()
}
deferRAII

defer 延迟执行

RAII 语法糖,作用域结束自动清理。RAII sugar — runs cleanup when scope ends.

_t_defer.hp
fn test_defer() {
    defer print("cleanup")
    print("main")
}

fn main() {
    test_defer()
}
namespace组织

命名空间

用 namespace 组织函数与类型。Organize functions and types with namespaces.

_t_namespace.hp
namespace utils {
    fn add(a: int, b: int) -> int {
        return a + b
    }
    fn multiply(a: int, b: int) -> int {
        return a * b
    }
}

fn main() {
    sum = utils.add(3, 4)
    prod = utils.multiply(2, 5)
    print(sum, prod)
}
arithmeticif

算术与分支

整数/浮点混合运算与条件分支。Mixed integer/float math with conditionals.

arithmetic.hp
module {
    "<std>"
}

fn main() {
    a = 10
    b = 20
    c = a + b
    std.io.print(c)

    d = 3.14
    e = 2.5
    f = d * e
    std.io.print(f)

    x = 42
    if x > 10 {
        std.io.print(1)
    } else {
        std.io.print(0)
    }
}
genericsstruct

泛型 Generic

泛型结构体与泛型函数,单态化在编译期完成,零运行时开销。Generic structs and functions — monomorphization happens at compile time, zero runtime cost.

generics.hp
struct Pair[T, U] {
    first: T
    second: U
}

fn swap[T, U](p: Pair[T, U]) -> Pair[U, T] {
    return Pair { first: p.second, second: p.first }
}

fn main() {
    p = Pair { first: 10, second: "hp" }
    q = swap(p)
    print(q.first, q.second)   # "hp" 10
}
concurrencyparallel

数据并行 Parallel

parallel for 编译期展开为静态分片,simd 提示生成向量化指令;spawn 编译为 OS 原生线程。parallel for expands to static slices at compile time; simd emits vectorized code; spawn becomes an OS thread.

concurrency.hp
fn main() {
    # 数据并行 + SIMD:编译期静态分片 + 向量化
    parallel for i in 1..9 simd {
        std.io.print(i * i)
    }

    # 任务并行:spawn 编译期为 OS 原生线程
    spawn fn() {
        std.io.print("来自新线程")
    }
}
json容器

JSON 字面量

原生 json 字面量,键/值访问,编译期已知类型、无解析运行时。Native json literals with homogeneous access — types known at compile time, no parse runtime.

json.hp
fn main() {
    user = {"name": "Alice", "age": 25, "tags": ["a", "b"]}
    print(user["name"])      # Alice
    print(user["age"] + 1)   # 26
    print(user["tags"][0])   # a
}
pipelinemap

管道处理 Pipeline

用 |> 把数据从左向右流过 filter / map,最后 sum 聚合。Pipe data left-to-right through filter / map, then aggregate with sum.

pipeline.hp
fn main() {
    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    evens   = nums |> filter(fn(x) { return x % 2 == 0 })
    squared = evens |> map(fn(x) { return x * x })
    total   = sum(squared)
    print(total)   # 120
}
f-string格式化

格式化字符串

f-string 在编译期展开为字符串拼接,运行时零格式化开销。f-strings expand to string concatenation at compile time — zero formatting cost at runtime.

fstring.hp
fn main() {
    name = "HP"
    version = 1.0
    count = 3
    msg = f"语言 {name} v{version} 有 {count} 个范式"
    print(msg)
    print(f"{count * count} = {count}²")
}
asyncawait

异步协程 Async

async fn 编译期为状态机结构体,await 转换为 poll 调用,事件循环由标准库提供。async fn becomes a state-machine struct at compile time; await becomes a poll call; the event loop is from the stdlib.

async.hp
async fn compute() -> i64 {
    return 6 * 7
}

fn main() {
    future = compute()
    answer = await future
    print(answer)   # 42
}