hd-lang

Tour · 14 of 18

Modules

The program on the right totals a cart with helpers from another file.

#Files are modules

pub fn total(lines: List[Line]) -> i32:
    subtotal := lines.iter().map(fn(line: Line) -> i32: line.cents).sum()
    subtotal + fee(subtotal)

Each file is a module. Open the other tab to see src/pricing.hd, where total lives.

#pub

pub struct Line:
    pub item: string
    pub cents: i32

A declaration is private unless it says pub. Fields need their own pub. fee has none, so only pricing.hd can call it.

#use

use pkg.pricing.{Line, total}

use names the public items this file needs. pkg.pricing is the module in src/pricing.hd.

Run it. The cart costs 3650, under 5000, so the 499 fee applies. It prints total: 4149 cents.

Try it: change use pkg.pricing.{Line, total} to use pkg.pricing.{Line, total, fee} and press Run.

Run: Ctrl+Enter · Pages: Alt+← Alt+→