Skip to content

Instantly share code, notes, and snippets.

@Alan-Liang
Last active August 3, 2022 06:02
Show Gist options
  • Save Alan-Liang/e9e3a68c4299a1da1789fe4ded28033f to your computer and use it in GitHub Desktop.
Save Alan-Liang/e9e3a68c4299a1da1789fe4ded28033f to your computer and use it in GitHub Desktop.
Early explorations of the AnotherKit language
// -*- mode: Rust; -*-
class Complex (
RealType extends Math.Field = Float,
ImagType extends Math.Field = RealType,
) extends Math.Field {
constructor (real: RealType, imag: ImagType) {}
fn + (that: Complex) = Complex(real + that.real, imag + that.imag)
fn +-inverse = Complex(-real, -imag)
fn abs = (this * conj).real.sqrt()
fn * (that: Complex) = Complex(
real * that.real - imag * that.imag,
real * that.imag + imag * that.real,
)
fn *-inverse {
let divisor = (this * conj()).real
return Complex(real / divisor, imag / divisor)
}
fn conj = Complex(real, -imag)
static +-unit = Complex(RealType.+-unit, ImagType.+-unit)
static *-unit = Complex(RealType.*-unit, ImagType.+-unit)
static i = Complex(RealType.+-unit, ImagType.*-unit)
}
type 𝐙[i] = Complex Int
a = 𝐙[i](2, 3) // 2+3i
conj = a.conj() // 2-3i as 𝐙[i]
b = 𝐙[i](3, 4) // 3+4i
add = a + b // 5+7i as 𝐙[i]
sub = a - b // -1-i as 𝐙[i]
mul = a * b // -6+17i as 𝐙[i]
div = a / b // -1.2+3.4i as Complex
// -*- mode: Rust; -*-
range(1, 101).for-each { x =>
if (x % 3 == 0) {
print(x % 5 == 0 ? 'FizzBuzz' : 'Fizz')
} else if (x % 5 == 0) {
print('Buzz')
}
}
// -*- mode: Rust; -*-
let str = 'Hello World!'
print(str)
str.print()
// -*- mode: Rust; -*-
decorator return-if-empty (sorted: Array a -> Array a) = { array: Array a =>
array.length <= 1 ? array : array.sorted()
}
// TODO: decorator syntax
@return-if-empty
export fn quick-sort (array: Array a) = [
...array.filter{ it < array[0] }.quick-sort(),
array[0],
...array.filter{ it >= array[0] }.quick-sort(),
]
@return-if-empty
export fn bubble-sort (var array: Array a) -> var Array a {
var sorted = false
while (!sorted) {
sorted = true
(array.length - 1).range { i =>
if array[i] > array[i + 1] {
sorted = false
array[i], array[i + 1] = array[i + 1], array[i]
}
}
}
return array
}
@return-if-empty
export fn selection-sort (array: Array a) = [
array.reduce { a, b => min(a, b) },
...array.slice(1).selection-sort(),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment