Skip to main content

Alia Syntax Examples

This document presents various syntax examples of the Alia language.

1. Basic Syntax​

1.1 Variable Declarations​

~ Declare variables
let x = 10
const y = 20

~ Variable declarations with type annotations
let name: String = 'Alice'
const age: Number = 30

1.2 Data Types​

~ Strings
const str1 = 'Hello'
const str2 = "World"

~ Numbers
const num1 = 42
const num2 = 3.14

~ Booleans
const bool1 = true
const bool2 = false

~ Arrays
const arr = [1, 2, 3, 4, 5]

~ Objects
const obj = *[ name: 'Alice', age: 30 ]

~ Stacks
const stack = *{
let x = 1
x + 1
}

1.3 Operators​

~ Arithmetic
const sum = 10 + 5
const difference = 10 - 5
const product = 10 * 5
const quotient = 10 / 5

~ Logical operations
const andResult = true & false
const orResult = true | false
const notResult = !true

~ Comparison
const greater = 10 > 5
const less = 10 < 5
const equal = 10 == 5

~ String concatenation
const greeting = 'Hello' .. ' ' .. 'World'

2. Control Flow​

2.1 if Statement​

const age = 18

if age >= 18 {
print 'Adult'
} else {
print 'Minor'
}

~ Nested if statements
const score = 85

if score >= 90 {
print 'Excellent'
} else {
if score >= 80 {
print 'Good'
} else {
if score >= 60 {
print 'Pass'
} else {
print 'Fail'
}
}
}

2.2 for Loop​

~ Print 1 to 10
for { let i = 0 } i < 10 { i ++ } {
print i
}

~ Iterate over an array
const arr = [1, 2, 3, 4, 5]
for { let i = 0 } i < arr.length { i ++ } {
print 'Element ' .. i .. ': ' .. arr[i]
}

2.3 while Loop​

~ Print 1 to 5
let i = 1
while i <= 5 {
print i
i ++
}

~ Condition-controlled loop
let count = 0
while count < 3 {
print 'Loop count: ' .. count
count ++
}

2.4 repeat Loop​

~ Infinite loop, exited via throw
let i = 0
try {
repeat {
print i
i ++
if i >= 5 {
throw 'done'
}
}
} catch e {
print e
}

3. Functions​

3.1 Basic Functions​

~ Define an addition function
const add = alias <Number a> and <Number b> -> Number { a + b }

~ Call the function
const result = add 1 and 2
print result

3.2 Functions with Return Values​

const multiply = alias <Number a> and <Number b> -> Number { a * b }

const product = multiply 3 and 4
print product

3.3 Anonymous Functions​

const subtract = alias <Number a> and <Number b> -> Number { a - b }

const difference = subtract 10 and 5
print difference

3.4 Higher-Order Functions​

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 Recursive Functions​

~ Compute the factorial
alias factorial <Number n> -> Number {
if n <= 1 {
return 1
} else {
return n * (factorial n - 1)
}
}

print (factorial 5)

~ Fibonacci sequence
alias fibonacci <Number n> -> Number {
if n <= 1 {
return n
} else {
return (fibonacci n - 1) + (fibonacci n - 2)
}
}

print (fibonacci 10)

4. Classes​

4.1 Basic Classes​

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 Classes with Methods​

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 Inheritance​

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. Error Handling​

5.1 try-catch​

try {
print 'Trying to execute'
throw 'An error occurred'
print 'This line will not execute'
} catch e {
print 'Caught error: ' .. e
}

5.2 Custom Errors​

try {
print 'Starting execution'
throw new Error ['Custom error', 'CustomError']
} catch e {
print 'Error message: ' .. e.message
print 'Error name: ' .. e.name
}

6. Standard Library​

6.1 File System​

import 'fs' as fs

~ Write a file
fs.write 'Hello World!' to 'example.txt'

~ Read the file
const content = fs.read 'example.txt'
print content

~ Check whether the file exists
const exists = fs.exist 'example.txt'
print 'File exists: ' .. exists

6.2 Process Management​

import 'process' as process

~ Get an environment variable
const home = process.envGet 'HOME'

~ Execute a command
const result = process.exec 'echo Hello'
print result.stdout

6.3 Built-in Objects​

~ Math operations
print 'PI: ' .. Math.PI
print 'E: ' .. Math.E
print 'Square root: ' .. (Math.sqrt 16)
print 'Absolute value: ' .. (Math.abs -10)
print 'Max: ' .. (Math.max 1 and 2 and 3 and 4 and 5)
print 'Min: ' .. (Math.min 1 and 2 and 3 and 4 and 5)

~ Date operations
const now = call Date.now
print 'Current time: ' .. now

const date = new Date [*[year: 2023, month: 11, day: 25]]
print 'Christmas: ' .. (date.toFormat 'YYYY-MM-DD')

7. Advanced Features​

7.1 Advanced Alias Usage​

~ Custom control structure
alias repeatTimes <Number times> times <Stack stack> -> {
for { let i = 0 } i < times { i ++ } {
call stack.run
}
}

~ Usage
repeatTimes 3 times {
print 'Hello'
}

~ Chained call
alias <Number num> squared -> Number {
num * num
}

print (5 squared)

7.2 Stack Operations​

~ Basic stack operations
const stack = *{
let x = 10
let y = 20
x + y
}

const result = call stack.run
print result

~ Stack context
const stack2 = mut *{
this.define 'name' 'Alice'
print name
}

call stack2.run

7.3 Mutable Stacks​

~ Mutable stack (persistent state)
const counter = mut *{
if Has 'count' {
count
} else {
let count = 1
count
}
}

print call counter.run ~ prints 1
counter.set 'count' 2
print call counter.run ~ prints 2
counter.set 'count' 3
print call counter.run ~ prints 3

~ this operations inside a mutable stack
const stack = mut *{
this.define 'name' 'Alice'
this.set 'name' 'Bob'
if this.has 'name' {
this.resolve 'name'
}
}
print call stack.run ~ prints 'Bob'

~ Recursive stack execution
let sum = 0
const recursiveStack = {
sum = sum + 1
if sum > 5 {
break
}
call this.run
}
call recursiveStack.run
print sum ~ prints 6

7.4 The enter Keyword​

~ Enter a stack context
const stack = mut *{
let val = 100
val
}
call stack.run

enter (stack) {
if Has 'val' {
print val ~ prints 100
}
}

7.5 Module Import and Export​

~ math.alia: export a module
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 a module
import 'math.alia' as math

print (math.add 1 and 2)
print (math.subtract 5 and 3)

8. Complete Examples​

8.1 Number Guessing Game​

~ Number guessing game
import 'io' as io

print 'Number Guessing Game'
print "I'm thinking of a number between 1 and 100. Can you guess it?"

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 'Enter your guess: '
const line = await task
const guess = line as Number
attempts ++
if guess < target {
print 'Too small!'
} else {
if guess > target {
print 'Too big!'
} else {
print 'Congratulations, you got it!'
print 'You took ' .. attempts .. ' attempts'
found = true
}
}
}

8.2 Todo List​

~ Todo list
type Todo *[task: String, completed: Boolean]

let todos: [Todo, ...] = []

alias addTodo <String task> -> {
const record: Todo = *[ task: task, completed: false ]
todos.push record
print 'Added task: ' .. task
}

alias listTodos -> {
print 'Todos:'
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 'Completed task: ' .. todos[index].task
} else {
print 'Invalid task index'
}
}

~ Usage
addTodo 'Learn the Alia language'
addTodo 'Finish the project'
addTodo 'Exercise'

call listTodos

completeTodo 0

call listTodos

Next Steps​