Alia 语法示例
本文档展示了 Alia 语言的各种语法示例。
1. 基础语法
1.1 变量声明
~ 声明变量
let x = 10
const y = 20
~ 带类型注解的变量声明
let name: String = 'Alice'
const age: Number = 30
1.2 数据类型
~ 字符串
const str1 = 'Hello'
const str2 = "World"
~ 数字
const num1 = 42
const num2 = 3.14
~ 布尔值
const bool1 = true
const bool2 = false
~ 数组
const arr = [1, 2, 3, 4, 5]
~ 对象
const obj = *[ name: 'Alice', age: 30 ]
~ 栈
const stack = *{
let x = 1
x + 1
}
1.3 运算符
~ 四则运算
const sum = 10 + 5
const difference = 10 - 5
const product = 10 * 5
const quotient = 10 / 5
~ 逻辑运算
const andResult = true & false
const orResult = true | false
const notResult = !true
~ 大小比较
const greater = 10 > 5
const less = 10 < 5
const equal = 10 == 5
~ 字符串连接
const greeting = 'Hello' .. ' ' .. 'World'
2. 控制流
2.1 if 语句
const age = 18
if age >= 18 {
print '成年人'
} else {
print '未成年人'
}
~ 嵌套 if 语句
const score = 85
if score >= 90 {
print '优秀'
} else {
if score >= 80 {
print '良好'
} else {
if score >= 60 {
print '及格'
} else {
print '不及格'
}
}
}
2.2 for 循环
~ 打印 1 到 10
for { let i = 0 } i < 10 { i ++ } {
print i
}
~ 遍历数组
const arr = [1, 2, 3, 4, 5]
for { let i = 0 } i < arr.length { i ++ } {
print '元素 ' .. i .. ': ' .. arr[i]
}
2.3 while 循环
~ 打印 1 到 5
let i = 1
while i <= 5 {
print i
i ++
}
~ 条件控制循环
let count = 0
while count < 3 {
print '循环次数: ' .. count
count ++
}
2.4 repeat 循环
~ 无限循环,以 throw 跳出
let i = 0
try {
repeat {
print i
i ++
if i >= 5 {
throw 'done'
}
}
} catch e {
print e
}
3. 函数
3.1 基本函数
~ 定义加法函数
const add = alias <Number a> and <Number b> -> Number { a + b }
~ 调用函数
const result = add 1 and 2
print result
3.2 带返回值的函数
const multiply = alias <Number a> and <Number b> -> Number { a * b }
const product = multiply 3 and 4
print product
3.3 匿名函数
const subtract = alias <Number a> and <Number b> -> Number { a - b }
const difference = subtract 10 and 5
print difference
3.4 高阶函数
const applyOperation = alias <Alias op> and <Number a> and <Number b> -> Number {
call op [a, b]
}
const add = alias <Number x> and <Number y> -> Number { x + y }
const result = applyOperation add and 5 and 3
print result
3.5 递归函数
~ 计算阶乘
alias factorial <Number n> -> Number {
if n <= 1 {
return 1
} else {
return n * (factorial n - 1)
}
}
print (factorial 5)
~ 斐波那契数列
alias fibonacci <Number n> -> Number {
if n <= 1 {
return n
} else {
return (fibonacci n - 1) + (fibonacci n - 2)
}
}
print (fibonacci 10)
4. 类
4.1 基本类
class Person *[
name: '',
age: 0,
new: alias <String name> and <Number age> -> {
self.name = name
self.age = age
self
}
]
const person = new Person *[name: 'Alice', age: 30]
print person.name .. ' is ' .. person.age .. ' years old'
4.2 带方法的类
class Person *[
name: '',
age: 0,
greet: alias -> {
'Hello, my name is ' .. self.name
},
celebrateBirthday: alias -> {
self.age += 1
'Happy birthday! You are now ' .. self.age .. ' years old'
},
new: alias <String name> and <Number age> -> {
self.name = name
self.age = age
self
}
]
const person = new Person *[name: 'Bob', age: 25]
print (call person.greet)
print (call person.celebrateBirthday)
4.3 类的继承
class Animal *[
name: '',
speak: alias -> {
'Animal sound'
},
new: alias <String name> -> {
self.name = name
self
}
]
class Dog extends Animal *[
breed: '',
speak: alias -> {
'Woof! Woof!'
}
]
const dog = new Dog *[name: 'Rex']
dog.breed = 'German Shepherd'
print dog.name .. ' says ' .. (call dog.speak)
5. 错误处理
5.1 try-catch
try {
print '尝试执行'
throw '发生错误'
print '这行不会执行'
} catch e {
print '捕获到错误: ' .. e
}
5.2 自定义错误
try {
print '开始执行'
throw new Error ['自定义错误', 'CustomError']
} catch e {
print '错误信息: ' .. e.message
print '错误名称: ' .. e.name
}
6. 标准库
6.1 文件系统
import 'fs' as fs
~ 写入文件
fs.write 'Hello World!' to 'example.txt'
~ 读取文件
const content = fs.read 'example.txt'
print content
~ 检查文件是否存在
const exists = fs.exist 'example.txt'
print '文件存在: ' .. exists
6.2 进程管理
import 'process' as process
~ 获取环境变量
const home = process.envGet 'HOME'
~ 执行命令
const result = process.exec 'echo Hello'
print result.stdout
6.3 内置对象
~ 数学运算
print 'PI: ' .. Math.PI
print 'E: ' .. Math.E
print '平方根: ' .. (Math.sqrt 16)
print '绝对值: ' .. (Math.abs -10)
print '最大值: ' .. (Math.max 1 and 2 and 3 and 4 and 5)
print '最小值: ' .. (Math.min 1 and 2 and 3 and 4 and 5)
~ 日期操作
const now = call Date.now
print '当前时间: ' .. now
const date = new Date [*[year: 2023, month: 11, day: 25]]
print '圣诞节: ' .. (date.toFormat 'YYYY-MM-DD')
7. 高级特性
7.1 Alias 高级用法
~ 自定义控制结构
alias repeatTimes <Number times> times <Stack stack> -> {
for { let i = 0 } i < times { i ++ } {
call stack.run
}
}
~ 使用
repeatTimes 3 times {
print 'Hello'
}
~ 链式调用
alias <Number num> squared -> Number {
num * num
}
print (5 squared)
7.2 栈操作
~ 基本栈操作
const stack = *{
let x = 10
let y = 20
x + y
}
const result = call stack.run
print result
~ 栈的语境
const stack2 = mut *{
this.define 'name' 'Alice'
print name
}
call stack2.run
7.3 可变栈
~ 可变栈(状态持久化)
const counter = mut *{
if Has 'count' {
count
} else {
let count = 1
count
}
}
print call counter.run ~ 输出 1
counter.set 'count' 2
print call counter.run ~ 输出 2
counter.set 'count' 3
print call counter.run ~ 输出 3
~ 可变栈内的 this 操作
const stack = mut *{
this.define 'name' 'Alice'
this.set 'name' 'Bob'
if this.has 'name' {
this.resolve 'name'
}
}
print call stack.run ~ 输出 'Bob'
~ 栈递归执行
let sum = 0
const recursiveStack = {
sum = sum + 1
if sum > 5 {
break
}
call this.run
}
call recursiveStack.run
print sum ~ 输出 6
7.4 enter 关键字
~ 进入栈语境
const stack = mut *{
let val = 100
val
}
call stack.run
enter (stack) {
if Has 'val' {
print val ~ 输出 100
}
}
7.5 模块导入导出
~ math.alia:导出模块
const math = *[
add: alias <Number a> and <Number b> -> Number { a + b },
subtract: alias <Number a> and <Number b> -> Number { a - b }
]
export math
~ main.alia:导入模块
import 'math.alia' as math
print (math.add 1 and 2)
print (math.subtract 5 and 3)
8. 完整示例
8.1 猜数字游戏
~ 猜数字游戏
import 'io' as io
print '猜数字游戏'
print '我想了一个 1 到 100 之间的数字,你能猜出来吗?'
const raw = call Math.random
const scaled = raw * 100 + 1
const target = Math.floor scaled
let attempts = 0
let found = false
while !found {
const task = io.readLine '请输入你的猜测: '
const line = await task
const guess = line as Number
attempts ++
if guess < target {
print '太小了!'
} else {
if guess > target {
print '太大了!'
} else {
print '恭喜你猜对了!'
print '你用了 ' .. attempts .. ' 次尝试'
found = true
}
}
}
8.2 待办事项列表
~ 待办事项列表
type Todo *[task: String, completed: Boolean]
let todos: [Todo, ...] = []
alias addTodo <String task> -> {
const record: Todo = *[ task: task, completed: false ]
todos.push record
print '添加了任务: ' .. task
}
alias listTodos -> {
print '待办事项:'
for { let i = 0 } i < todos.length { i ++ } {
const todo = todos[i]
const status = todo.completed ? '✓' : '✗'
print (i + 1) .. '. ' .. status .. ' ' .. todo.task
}
}
alias completeTodo <Number index> -> {
if index >= 0 & index < todos.length {
todos[index].completed = true
print '已完成任务: ' .. todos[index].task
} else {
print '无效的任务索引'
}
}
~ 使用
addTodo '学习 Alia 语言'
addTodo '完成项目'
addTodo '锻炼身体'
call listTodos
completeTodo 0
call listTodos