역 폴란드 식 의 실현

928 단어
  • 데이터 구조
    data Lex = Number Double Lex
     | Plus Lex
     | Times Lex
     | End deriving Show
    
  • 해석
    lexRPN :: String -> Lex
    lexRPN = go . words
     where 
      go ("*":rest) = Times (go rest)
      go ("+":rest) = Plus (go rest)
      go (num:rest) = Number (read num) (go rest)
      go [] = End
    
  • 데이터 구조의 의미
    evalRPN :: Lex -> Double
    evalRPN = go [] where
      go stack (Number num rest) = go (num : stack) rest
      go (o1:o2:stack) (Plus rest)= let r = o1 + o2 in r `seq` go (r : stack) rest
      go (o1:o2:stack) (Times rest)= let r = o1 * o2 in r `seq` go (r : stack) rest
      go [res] End = res 
    
  • 테스트
    ghci> lexRPN "3 1 2 + *"
    Number 3.0 (Number 1.0 (Number 2.0 (Plus (Times End))))
    ghci> evalRPN $ lexRPN "3 1 2 + *"
    9.0
    ghci> evalRPN $ lexRPN "5 6 2 + 7 * *"
    280.0
    ghci>
  • 좋은 웹페이지 즐겨찾기