Haskell解决逆波兰式
摘自<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