Skip to content

Instantly share code, notes, and snippets.

@dusty-phillips
Last active April 2, 2023 20:10
Show Gist options
  • Save dusty-phillips/48c0dd17f83043a7432d0fb77a2e1b2b to your computer and use it in GitHub Desktop.
Save dusty-phillips/48c0dd17f83043a7432d0fb77a2e1b2b to your computer and use it in GitHub Desktop.
import std::fmt::(Format, Formatter, fmt)
import std::stdio::STDOUT
class Node[T: Format] {
let @next: Option[Node[T]]
let @prev: Option[mut Node[T]]
let @data: T
fn pub static new(value: T) -> Self {
Node {
@next = Option.None
@prev = Option.None
@data = value
}
}
}
impl Format for Node {
fn pub fmt(formatter: mut Formatter) {
@prev.as_ref.map fn (p) {
formatter.write("(")
p.data.fmt(formatter)
formatter.write(")")
}
@data.fmt(formatter)
@next.as_ref.map fn (n) {
formatter.write("(")
n.data.fmt(formatter)
formatter.write(")")
}
formatter.write(" ")
}
}
class List[T: Format] {
let @tail: Option[mut Node[T]]
let @head: Option[Node[T]]
fn pub static new() -> Self {
List {
@head = Option.None
@tail = Option.None
}
}
fn pub mut push_left(value: T) {
let node = Node.new(value)
let node_mut = mut node
match @head := Option.Some(node) {
case None -> {
@tail = Option.Some(node_mut)
}
case Some(head) -> {
head.prev = Option.Some(node_mut)
node_mut.next = Option.Some(head)
}
}
}
}
impl Format for List {
fn pub fmt(formatter: mut Formatter) {
let mut current = @head
loop {
match current {
case None -> {
formatter.write("#")
break
}
case Some(value) -> {
value.fmt(formatter)
formatter.write(" -> ")
current = value.next
}
}
}
}
}
class async Main {
fn pub async main() {
let list = List.new
list.push_left(4)
list.push_left(3)
list.push_left(2)
list.push_left(1)
STDOUT.new.print(fmt(list))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment