Skip to content

Instantly share code, notes, and snippets.

@jooyunghan
Created October 26, 2015 07:42
Show Gist options
  • Save jooyunghan/303c19c1c1db9508fda7 to your computer and use it in GitHub Desktop.
Save jooyunghan/303c19c1c1db9508fda7 to your computer and use it in GitHub Desktop.
Haskell 간단 파싱 예제 (Text.Parsec)
import Text.Parsec (parse, char, (<|>))
import Text.Parsec.Char (spaces)
import Text.Parsec.Language (haskell)
import Text.Parsec.String (Parser)
import Text.Parsec.Token (makeTokenParser, integer, parens, whiteSpace, identifier)
data Tree a = Leaf a | Branch (Tree a) a (Tree a) deriving (Show)
int :: Parser Int
int = integer haskell >>= return.fromInteger
tree :: Parser a -> Parser (Tree a)
tree node = leaf node <|> branch node
leaf :: Parser a -> Parser (Tree a)
leaf node = node >>= return.Leaf
branch :: Parser a -> Parser (Tree a)
branch node = whiteSpace haskell >> parens haskell (Branch <$> tree node <*> node <*> tree node)
main :: IO()
main = do
print $ parse (branch int) "" " ( 1 2 ( 3 4 5))"
print $ parse (leaf int) "" " 23 "
print $ parse (tree (identifier haskell)) "" " (a abc (def root xxx)) "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment