vlib: add an `adt` module (Abstract Data Types) (#12901)

pull/12937/head^2
Hunam 2021-12-23 14:16:29 +01:00 committed by GitHub
parent d4f28c88b3
commit d7deda5078
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 97 additions and 0 deletions

View File

@ -0,0 +1,9 @@
# adt
A library providing common ADTs (Abstract Data Type) implementations which have proved useful in a
great variety of applications.
## implementations
- [x] Stack (LIFO)
- [ ] ...

36
vlib/adt/stack.v 100644
View File

@ -0,0 +1,36 @@
module adt
pub struct Stack<T> {
mut:
elements []T
}
// is_empty checks if the stack is empty
pub fn (stack Stack<T>) is_empty() bool {
return stack.elements.len == 0
}
// len returns the length of the stack
pub fn (stack Stack<T>) len() int {
return stack.elements.len
}
// peek returns the top of the stack
pub fn (stack Stack<T>) peek() ?T {
return if !stack.is_empty() { stack.elements.last() } else { error('Stack is empty') }
}
// push adds an element to the top of the stack
pub fn (mut stack Stack<T>) push(item T) {
stack.elements << item
}
// pop removes the element at the top of the stack and returns it
pub fn (mut stack Stack<T>) pop() ?T {
return if !stack.is_empty() { stack.elements.pop() } else { error('Stack is empty') }
}
// str returns a string representation of the stack
pub fn (stack Stack<T>) str() string {
return stack.elements.str()
}

View File

@ -0,0 +1,52 @@
import adt
fn test_is_empty() {
mut stack := adt.Stack<int>{}
assert stack.is_empty() == true
stack.push(1)
assert stack.is_empty() == false
}
fn test_len() ? {
mut stack := adt.Stack<int>{}
assert stack.len() == 0
stack.push(1)
assert stack.len() == 1
stack.pop() ?
assert stack.len() == 0
}
fn test_peek() ? {
mut stack := adt.Stack<int>{}
stack.push(1)
assert stack.peek() ? == 1
stack.push(2)
assert stack.peek() ? == 2
stack = adt.Stack<int>{}
stack.peek() or { return }
assert false
}
fn test_push() ? {
mut stack := adt.Stack<int>{}
stack.push(1)
assert stack.peek() ? == 1
stack.push(2)
assert stack.peek() ? == 2
stack.push(3)
assert stack.peek() ? == 3
}
fn test_pop() ? {
mut stack := adt.Stack<int>{}
stack.push(1)
stack.push(2)
stack.push(3)
assert stack.pop() ? == 3
stack.push(4)
assert stack.pop() ? == 4
assert stack.pop() ? == 2
stack = adt.Stack<int>{}
stack.pop() or { return }
assert false
}