RosettaCodeData/Task/Queue-Definition/V-(Vlang)/queue-definition.v

51 lines
1.1 KiB
Coq
Raw Permalink Normal View History

2023-07-01 11:58:00 -04:00
const max_tail = 256
2026-04-30 12:34:36 -04:00
struct Queue[T] {
mut:
2023-07-01 11:58:00 -04:00
data []T
2026-04-30 12:34:36 -04:00
tail int
2023-07-01 11:58:00 -04:00
head int
}
2026-04-30 12:34:36 -04:00
fn (mut queue Queue[T]) push(value T) {
if queue.tail >= max_tail || queue.tail < queue.head { return }
println("Enqueue: $value")
2023-07-01 11:58:00 -04:00
queue.data << value
queue.tail++
}
2026-04-30 12:34:36 -04:00
fn (mut queue Queue[T]) pop() !T {
2023-07-01 11:58:00 -04:00
if queue.tail > 0 && queue.head < queue.tail {
result := queue.data[queue.head]
queue.head++
2026-04-30 12:34:36 -04:00
println("Dequeue: top of Queue was $result")
2023-07-01 11:58:00 -04:00
return result
}
2026-04-30 12:34:36 -04:00
return error("Queue Underflow!!")
2023-07-01 11:58:00 -04:00
}
2026-04-30 12:34:36 -04:00
fn (queue Queue[T]) peek() !T {
2023-07-01 11:58:00 -04:00
if queue.tail > 0 && queue.head < queue.tail {
result := queue.data[queue.head]
2026-04-30 12:34:36 -04:00
println("Peek: top of Queue is $result")
2023-07-01 11:58:00 -04:00
return result
}
2026-04-30 12:34:36 -04:00
return error("Out of Bounds...")
2023-07-01 11:58:00 -04:00
}
2026-04-30 12:34:36 -04:00
fn (queue Queue[T]) empty() bool {
2023-07-01 11:58:00 -04:00
return queue.tail == 0
}
fn main() {
2026-04-30 12:34:36 -04:00
mut queue := Queue[f64]{}
println("Queue is empty? " + if queue.empty() { "Yes" } else { "No" })
2023-07-01 11:58:00 -04:00
queue.push(5.0)
queue.push(4.2)
2026-04-30 12:34:36 -04:00
println("Queue is empty? " + if queue.empty() { "Yes" } else { "No" })
2023-07-01 11:58:00 -04:00
queue.peek() or { return }
queue.pop() or { return }
queue.pop() or { return }
queue.push(1.2)
}