Exercises
Stack as package
See the Stack exercise. In this exercise we want to create a separate packagefor that code. Create a proper package for your stack implementation,
Push
,Pop
and theStack
type need to be exported.Write a simple unit test for this package.You should at least test that a
Pop
works after aPush
.
Answer
- There are a few details that should be changed to make a proper packagefor our stack. First, the exported functions should begin with a capitalletter and so should
Stack
. The package file is namedstack-as-package.go
and contains:
package stack
// Stack holds the items.
type Stack struct {
i int
data [10]int
}
// Push pushes an item on the stack.
func (s *Stack) Push(k int) {
s.data[s.i] = k
s.i++
}
// Pop pops an item from the stack.
func (s *Stack) Pop() (ret int) {
s.i--
ret = s.data[s.i]
return
}
- To make the unit testing work properly you need to do somepreparations. We’ll come to those in a minute. First the actual unit test.Create a file with the name
pushpop_test.go
, with the following contents:
package stack
import "testing"
func TestPushPop(t *testing.T) {
c := new(Stack)
c.Push(5)
if c.Pop() != 5 {
t.Log("Pop doesn't give 5")
t.Fail()
}
}
For go test
to work we need to put our package files in a directoryunder $GOPATH/src
:
% mkdir $GOPATH/src/stack
% cp pushpop_test.go $GOPATH/src/stack
% cp stack-as-package.go $GOPATH/src/stack
Yields:
% go test stack
ok stack 0.001s
Calculator
- Create a reverse polish calculator. Use your stack package.
Answer
- This is one answer:
package main
import (
"bufio"
"fmt"
"os"
"strconv"
)
var reader *bufio.Reader = bufio.NewReader(os.Stdin)
var st = new(Stack)
type Stack struct {
i int
data [10]int
}
func (s *Stack) push(k int) {
if s.i+1 > 9 {
return
}
s.data[s.i] = k
s.i++
}
func (s *Stack) pop() (ret int) {
s.i--
if s.i < 0 {
s.i = 0
return
}
ret = s.data[s.i]
return
}
func main() {
for {
s, err := reader.ReadString('\n')
var token string
if err != nil {
return
}
for _, c := range s {
switch {
case c >= '0' && c <= '9':
token = token + string(c)
case c == ' ':
r, _ := strconv.Atoi(token)
st.push(r)
token = ""
case c == '+':
fmt.Printf("%d\n", st.pop()+st.pop())
case c == '*':
fmt.Printf("%d\n", st.pop()*st.pop())
case c == '-':
p := st.pop()
q := st.pop()
fmt.Printf("%d\n", q-p)
case c == 'q':
return
default:
//error
}
}
}
}
当前内容版权归 Miek Gieben 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 Miek Gieben .