Created
July 11, 2014 23:04
-
-
Save bahlo/3c5fb843eff39a44ffc1 to your computer and use it in GitHub Desktop.
A RPN calculator: Haskell vs. Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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