Skip to content

Instantly share code, notes, and snippets.

@igrep
Last active December 11, 2015 09:08
Show Gist options
  • Select an option

  • Save igrep/4578170 to your computer and use it in GitHub Desktop.

Select an option

Save igrep/4578170 to your computer and use it in GitHub Desktop.
Excercise from "Learn You a Haskell for Great Good!"
module RPNWriter where
-- 逆ポーランド記法で書かれた式を計算する関数 solveRPN (p.214) に、
-- Writerモナドを使って計算経過ログをとる機能を追加してみよう。
import Control.Monad.Writer
import Control.Applicative ((<$>))
import Data.Char (isDigit)
solveRPNwithLog :: String -> Writer String Double
solveRPNwithLog s = do
head <$> (foldM foldingFunctionWithLog [] $ words s)
where
foldingFunction (x:y:ys) "*" = (y * x) : ys
foldingFunction (x:y:ys) "+" = (y + x) : ys
foldingFunction (x:y:ys) "-" = (y - x) : ys
foldingFunction xs str = read str : xs
foldingFunctionWithLog :: [Double] -> String -> Writer String [Double]
foldingFunctionWithLog xs str
| all isDigit str = do
tell $ "Read " ++ str ++ ".\n"
return $ foldingFunction xs str
| otherwise = do
let x:y:_ = xs
tell $ "Apply " ++ str ++ " on " ++ show x ++ " and " ++ show y ++ ".\n"
return $ foldingFunction xs str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment