Skip to content

Instantly share code, notes, and snippets.

@taisyo7333
Last active August 29, 2015 14:25
Show Gist options
  • Save taisyo7333/c0afd3ed89b782100e18 to your computer and use it in GitHub Desktop.
Save taisyo7333/c0afd3ed89b782100e18 to your computer and use it in GitHub Desktop.
translate InFix notation into PostFix notation.
>ghci Translate.hs
GHCi, version 7.8.3: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling Translate ( Translate.hs, interpreted )
Ok, modules loaded: Translate.
*Translate> translate "1 + 2 * 3 ^ 4"
Loading package array-0.5.0.0 ... linking ... done.
Loading package deepseq-1.3.0.2 ... linking ... done.
Loading package containers-0.5.5.1 ... linking ... done.
"1 2 3 4 ^ * +"
*Translate> translate "1 + 2 * 3 + 4"
"1 2 3 * + 4 +"
*Translate> translate "1 + 2 * 3 * 4"
"1 2 3 * 4 * +"
*Translate> translate "1 + 2 * 3 / 4"
"1 2 3 * 4 / +"
*Translate>
module Translate
( toPostFix
, translate
) where
import Data.Char
import qualified Data.Map as Map
-- ("operator",priority)
operators = Map.fromList [ ("+",1)
, ("-",1)
, ("*",2)
, ("/",2)
, ("^",3)
]
type Stack = [String]
translate :: String -> String
translate src = unwords . toPostFix [] $ words src
-- Translate from InFix to PostFix
toPostFix :: Stack -> [String] -> [String]
toPostFix [] [] = []
toPostFix [] (token:lestToken)
| Nothing /= priToken = toPostFix [token] lestToken
| True == isNum token = token : ( toPostFix [] lestToken )
| otherwise = error "token parse error #1"
where priToken = Map.lookup token operators
toPostFix (op:stk) [] = op : toPostFix stk []
toPostFix (op:stk) (token:lestToken)
| Nothing /= priToken && ( priOp >= priToken ) = op : toPostFix (stk) (token:lestToken)
| Nothing /= priToken && ( priOp < priToken ) = toPostFix (token:op:stk) lestToken
| True == isNum token = token : ( toPostFix (op:stk) lestToken )
| otherwise = error "token parse error #2"
where priOp = Map.lookup op operators
priToken = Map.lookup token operators
isNum :: String -> Bool
isNum src = src == filter (\x -> isDigit x ) src
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment