Last active
December 11, 2015 09:08
-
-
Save igrep/4578170 to your computer and use it in GitHub Desktop.
Excercise from "Learn You a Haskell for Great Good!"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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