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
本文介绍了一种使用Haskell语言解决逆波兰表达式的算法。该算法通过递归方式处理输入字符串,并针对不同的数学运算符进行计算。文章提供了一个具体的实现示例,并展示了几个运行实例。

被折叠的 条评论
为什么被折叠?



