Skip to content

Instantly share code, notes, and snippets.

@bahlo
Created July 11, 2014 23:04
Show Gist options
  • Save bahlo/3c5fb843eff39a44ffc1 to your computer and use it in GitHub Desktop.
Save bahlo/3c5fb843eff39a44ffc1 to your computer and use it in GitHub Desktop.
A RPN calculator: Haskell vs. Go
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func solveRPN(line string) int {
stack := []int{}
input := strings.Split(line[:len(line)-1], " ")
for _, v := range input {
if v == "*" {
stack = append(stack[:len(stack)-2], stack[len(stack)-2]*stack[len(stack)-1])
} else if v == "+" {
stack = append(stack[:len(stack)-2], stack[len(stack)-2]+stack[len(stack)-1])
} else if v == "-" {
stack = append(stack[:len(stack)-2], stack[len(stack)-2]-stack[len(stack)-1])
} else {
value, _ := strconv.Atoi(v)
stack = append(stack, value)
}
}
return stack[len(stack)-1]
}
func main() {
fmt.Println("Your calculation: ")
reader := bufio.NewReader(os.Stdin)
line, _ := reader.ReadString('\n')
fmt.Println(solveRPN(line))
}
import Data.List
main = do
putStrLn "Your calculation: "
exp <- getLine
print $ solveRPN exp
solveRPN :: (Num a, Read a) => String -> a
solveRPN = head . foldl foldingFunction [] . words
where foldingFunction (x:y:ys) "*" = (x * y):ys
foldingFunction (x:y:ys) "+" = (x + y):ys
foldingFunction (x:y:ys) "-" = (y - x):ys
foldingFunction xs numberString = read numberString:xs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment