Haskellで数式をパースする
使い方
:load で読み込んだ後
myEquation "1+2*3"
import Text.ParserCombinators.Parsec myDigit :: Parser Char myDigit = oneOf ['0'..'9'] myNumberString :: Parser String myNumberString = do c<-myDigit do cs <- myNumberString return (c:cs) <|> return [c] myNumber :: Parser Integer myNumber = do s<-myNumberString return (read s) myPlusMinus :: Parser Char myPlusMinus = oneOf "+-" myMultiDiv :: Parser Char myMultiDiv = oneOf "*/" myCalc '+' left right = (left+right) myCalc '-' left right = (left-right) myCalc '*' left right = (left*right) myCalc '/' _ 0 = 0 myCalc '/' left right = (left `div` right) myEquation :: Parser Integer myEquation = do{ left<-myFactor; rest left } where rest l = do{ op<-myPlusMinus ;r<-myFactor ;rest (myCalc op l r) } <|> return l {-<|> do{ op<-myPlusMinus ;right<-myEquation ;return (myCalc op x right }-} myFactor :: Parser Integer --myFactor = do{ x<-myTerm; rest x} myFactor = do {left<-myTerm; rest left } where rest l = do{ op<-myMultiDiv ;r<-myTerm ;rest (myCalc op l r) } <|> return l {- left<-myFactor op<-myMultiDiv right<-myTerm return (myCalc op left right) <|> myTerm-} myTerm :: Parser Integer myTerm = do char '(' x<-myEquation char ')' return x <|> myNumber {- myExpr2List String->[String] myExpr2List "" = "" myExpr2List x:xs = if myPlusMinus myFactor :: Parser Integer myFactor = do char '(' x<-myExpr char ')' return x <|> myExpr myExpr :: Parser Integer myExpr = do left<-myNumber do op<-myPlusMinus right<-myFactor return (myCalc op left right) <|> return left <|> myFactor -}