码迷,mamicode.com
首页 > 其他好文 > 详细

Haskell解决逆波兰式

时间:2015-05-16 00:07:22      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

摘自<Haskell趣学指南- Learn You a Haskell for Great Good>

{-
逆波兰式(revese polish notation, RPN): 操作符出现在操作数的后面,而不是夹在它们中间. 如我们使用 "4 3 +" 而不是 "4 + 3".
-}

solveRPN :: String -> Double
solveRPN = head . foldl foldingFunction [] . words
    where foldingFunction (x:y:ys) "*" = (y * x ) : ys
          foldingFunction (x:y:ys) "+" = (y + x ) : 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
          

 

*Main> :l solveRPN.hs 
[1 of 1] Compiling Main             ( solveRPN.hs, interpreted )
Ok, modules loaded: Main.
*Main> solveRPN "2 3.5 +"
5.5
*Main> solveRPN "2 3.5 -"
-1.5
*Main> solveRPN "1 2 /"
0.5
*Main> solveRPN "3 2 *"
6.0
*Main> solveRPN "3 2 ^"
9.0
*Main> solveRPN "3 2 sum"
5.0
*Main> solveRPN "3 2 1 2sum"
*** Exception: Prelude.read: no parse
*Main> solveRPN "3 2 1 2 sum"
8.0
*Main> solveRPN "2.7 ln"
0.9932517730102834
*Main> solveRPN "2.7 ln 1 sum"
1.9932517730102834
*Main> 

 

编译hs文件:

$ghc --make file_name

不编译解释运行:

$runghc file_name.hs

 

Haskell解决逆波兰式

标签:

原文地址:http://www.cnblogs.com/wucg/p/4506993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!