Skip to content

Instantly share code, notes, and snippets.

@matsubara0507
Created December 7, 2016 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsubara0507/63bc7c3098899034db1a42f83e2c2dbb to your computer and use it in GitHub Desktop.
Save matsubara0507/63bc7c3098899034db1a42f83e2c2dbb to your computer and use it in GitHub Desktop.
二項演算だけパースする minruby パーサー
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