haskell - Functionally solving problems - Rerverse Polish Notation Caculator

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

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

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值