Created
December 7, 2016 16:02
-
-
Save matsubara0507/63bc7c3098899034db1a42f83e2c2dbb to your computer and use it in GitHub Desktop.
二項演算だけパースする minruby パーサー
This file contains 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 MinRuby | |
( minrubyParse | |
, minrubyLoad | |
) where | |
import Control.Applicative (empty) | |
import Data.Either (either) | |
import Data.Tree (Tree(..)) | |
import Text.Megaparsec (Parsec, Dec, parse, parseErrorPretty, some, string, space, (<|>)) | |
import Text.Megaparsec.Char (digitChar) | |
type MinRubyParser = Parsec Dec String | |
minrubyParse :: String -> Tree String | |
minrubyParse = either (error . parseErrorPretty) id | |
. parse minrubyParser "MinRuby Parser" | |
minrubyParser :: MinRubyParser (Tree String) | |
minrubyParser = space *> parseBinaryOp <* space | |
parseBinaryOp :: MinRubyParser (Tree String) | |
parseBinaryOp = do | |
n1 <- leaf <$> digit | |
space | |
op <- operator | |
space | |
n2 <- leaf <$> digit | |
return $ Node op [n1,n2] | |
digit :: MinRubyParser String | |
digit = some digitChar | |
operator :: MinRubyParser String | |
operator = foldl (<|>) empty $ fmap string binaryOps | |
binaryOps :: [String] | |
binaryOps = ["+", "-", "*", "/", "%"] | |
leaf :: a -> Tree a | |
leaf = flip Node [] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment