`

haskell - Functionally solving problems - Rerverse Polish Notation Caculator

阅读更多

So far we have introduced the basic construct that underpinning the haskell runtime and etc... Now we can come to the point where we leverage the haskell language to functinally solving some problems. 

 

the problem that we are going to solve in this post is the Reverse Polish Notation, which is a postfix notation of the mathmatical  operations, which normally represent 1 + 2 as 1 2 +; 

 

now that we want to develop some algorithm to to take a RPN notation string and then gives back the calculation result.

 

here is what we have developed, based on the fact we can use recursion and we can divide the problem into smaller ones, and each has a case calcuation based on the type of symbol that is current met on the input, the result will be put back on the top of the stack, here is the code. 

 

-- file 
--  reverseRPN2.hs
-- descrpition: 
--  solve the reverseRPN data issues


import Data.List  
  
solveRPN :: String -> Float  
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 (x:y:ys) "/" = (y / x):ys  
            foldingFunction (x:y:ys) "^" = (y ** x):ys  
            foldingFunction (x:xs) "ln" = log x:xs  
            foldingFunction xs "sum" = [sum xs]  
            foldingFunction xs numberString = read numberString:xs  

 

so let's explicate on the code, the code will check which is the current symbol that is under inspection, where it finds that if it is a '+' symbol, then it will add the immediate two numbers, which it will append the result (x + y) back to the head of the remaining of the arguments... and the calculation continues. 

 

Though the code does not deal with Exception so well, we will see later how we can better deal with Exceptions. (such as invalid input).

 

now let's see some live example of the function running on certain code.

ghci > solveRPN "10 4 3 + 2 * -"
-4
ghci > solveRPN "2 3 +"
5
ghci > solveRPN "90 34 12 33 55 66 + * - +"
-3947
ghci > solveRPN "90 34 12 33 55 66 + * - + -"
4037
ghci > solveRPN "90 34 12 33 55 66 + * - + -"
4037
ghci > solveRPN "90 3 -"
87

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics