Haskell逆ポーランド式解決

4757 ワード

から抜粋
{-
    (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