Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 63 lines (54 sloc) 1.196 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
package main

import (
"bufio"
"bytes"
"fmt"
"log"
"os"
"strconv"
)

type op_fn func(float64, float64) float64

var operators = map[byte]op_fn{
'+': func(a, b float64) float64 { return a + b },
'-': func(a, b float64) float64 { return a - b },
'*': func(a, b float64) float64 { return a * b },
'/': func(a, b float64) float64 { return a / b },
}

func main() {
log.SetFlags(0) // quieter logging

r := bufio.NewReader(os.Stdin)
stack := make([]float64, 0, 50)
for {
line, _, err := r.ReadLine()
if err != nil {
log.Fatal(err)
}
stack = process(line, stack)
log.Print(stack[len(stack)-1])
}

}

func process(line []byte, stack []float64) []float64 {
for _, sym := range bytes.Fields(line) {

op, ok := operators[sym[0]]
if ok {
tos := len(stack)
if tos < 2 {
fmt.Fprintf(os.Stderr, "Stack %v too small for %s\n",
stack, string(sym[0]))
return stack
}
stack[tos-2] = op(stack[tos-2], stack[tos-1])
stack = stack[:tos-1]
} else {
s := string(sym)
f, err := strconv.ParseFloat(s, 64)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return stack
}
stack = append(stack, f)
}
// log.Print(stack)
}
return stack
}
Something went wrong with that request. Please try again.