Stack: Difference between revisions

Content added Content deleted
Line 6,124: Line 6,124:
=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>const (
<lang vlang>const (
MaxDepth = 256
max_depth = 256
)
)


struct Stack {
struct Stack {
mut:
mut:
data []f32=[f32(0)].repeat(MaxDepth)
data []f32 = []f32{len: max_depth}
depth int=0
depth int
}
}


fn (s mut Stack) push(v f32) {
fn (mut s Stack) push(v f32) {
if s.depth >= MaxDepth {
if s.depth >= max_depth {
return
return
}
}
println('Push: ${v : 3.2f}')
println('Push: ${v:3.2f}')
s.data[s.depth] = v
s.data[s.depth] = v
s.depth++
s.depth++
}
}


fn (s mut Stack) pop() ?f32 {
fn (mut s Stack) pop() ?f32 {
if s.depth > 0 {
if s.depth > 0 {
s.depth--
s.depth--
result := s.data[s.depth]
result := s.data[s.depth]
println('Pop: top of stack was ${result :3.2f}')
println('Pop: top of stack was ${result:3.2f}')
return result
return result
}
}
return error('Stack Underflow!!')
return error('Stack Underflow!!')
}
}


fn (s Stack) peek() ?f32 {
fn (s Stack) peek() ?f32 {
if s.depth > 0 {
if s.depth > 0 {
result := s.data[s.depth - 1]
result := s.data[s.depth - 1]
println('Peek: top of stack is ${result :3.2f}')
println('Peek: top of stack is ${result:3.2f}')
return result
return result
}
}
return error('Out of Bounds...')
return error('Out of Bounds...')
}
}


fn (s Stack) empty() bool {
fn (s Stack) empty() bool {
return s.depth == 0
return s.depth == 0
}
}


fn main() {
fn main() {
mut stack := Stack{}
mut stack := Stack{}
println('Stack is empty? ' + if stack.empty() { 'Yes' } else { 'No' })
println('Stack is empty? ' + if stack.empty() { 'Yes' } else { 'No' })
stack.push(5.0)
stack.push(5.0)
stack.push(4.2)
stack.push(4.2)
println('Stack is empty? ' + if stack.empty() { 'Yes' } else { 'No' })
println('Stack is empty? ' + if stack.empty() { 'Yes' } else { 'No' })
stack.peek() or {
stack.peek() or { return }
stack.pop() or { return }
return
}
stack.pop() or { return }
stack.pop() or {
return
}
stack.pop() or {
return
}
}
}
</lang>
</lang>