Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
An example of complex numbers syntax in Slang
// Add some prefix operators to the grammar
group complexPre = "ℜ…", "ℑ…", "Re…", "Im…"
// Make them bind tighter than anything, so we don't need parens
control -> complexPre
relations -> complexPre
arithmetic -> complexPre
brackets -> complexPre
// Complex type with some operators
val class Complex ⟨_real: Double, _imag: Double⟩ {
def real() = _real
def imag() = _imag
def dot(v: Complex) = `intrinsic.dotproduct.v2f64`(data, v)
alias ∙ = dot
alias ℜ… = real
alias Re… = real
alias ℑ… = imag
alias Im… = imag
def magnitude() = √(_real² + _imag²)
alias |…| = magnitude
}
// Alias for the type and it's generated constructor function
type ℂ = Complex
alias ℂ = Complex
// Example based on LLVM Kaleidoscope tutorial http://llvm.org/docs/tutorial/LangImpl6.html#example
// Determine whether the specific location diverges.
// Solve for z = z^2 + c in the complex plane.
def mandelbrotConverger(z0: ℂ, c: ℂ, iters: Int) =
loop (i := iters, z := z0) while i < 1000 ∧ |z| ≤ 2.0
do (i := i + 1, z := ℂ⟨ℜ z² - ℑ z² + ℜ c, 2.0 * ℜ z * ℑ z + ℑ c⟩)
yield i
def mandelbrotConverge(z: ℂ) = mandelbrotConverger(z, z, 0)
// Compute and plot the mandlebrot set with the specified 2 dimensional range info.
def mandelbrotHelper(min: ℂ, max: ℂ, step: ℂ) =
loop(y := ℑ min) while y < ℑ max do {
loop(x := ℜ min) while x < ℜ max do {
printdensity(mandelbrotConverge(ℂ⟨x, y⟩));
(x + ℜ step)
};
putchar(10);
(y + ℑ step)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment