我正在用 SML 编写一个简单的计算器,我的代码需要支持 3 种括号:
( )
[ ]
{ }
里面的什么地方{ }
,都能出现{ } , [ ] , ( )
表情,
里面[ ]
,会出现[ ] , ( )
表情,
而在里面( )
,只能出现( )
表情。
意思是,它{ }
具有最高优先级,the [ ]
-middle priority,并且( )
具有最低优先级。
实现这一目标的最佳方法是什么?
我编写了一个大方法,其中包含在不同情况下运行的太多循环和递归,但我认为这不是最好的方法。
任何建议将不胜感激
问候
编辑 :
相关代码:
signature CalculatorOperation = sig
datatype token =
(* paranthesis *)
Lpar3 (* { *)
| Rpar3 (* } *)
| Lpar2 (* [ *)
| Rpar2 (* ] *)
| Lpar (* ( *)
| Rpar (* ) *)
结构 :
structure CalculatorOperation : CalculatorOperation = struct
datatype token =
(* paranthesis *)
Lpar3 (* { *)
| Rpar3 (* } *)
| Lpar2 (* [ *)
| Rpar2 (* ] *)
| Lpar (* ( *)
| Rpar (* ) *)
扫描仪:
fun stringScanner s [] = (toToken s,[])
| stringScanner s (c::l)
= case c::l of
#" "::r => if s = "" then (stringScanner "" l) else (toToken s,l)
(* paranthesis *)
| #"{"::r => if s = "" then (Lpar3,r) else (toToken s,c::l)
| #"}"::r => if s = "" then (Rpar3,r) else (toToken s,c::l)
| #"["::r => if s = "" then (Lpar2,r) else (toToken s,c::l)
| #"]"::r => if s = "" then (Rpar2,r) else (toToken s,c::l)
| #"("::r => if s = "" then (Lpar,r) else (toToken s,c::l)
| #")"::r => if s = "" then (Rpar,r) else (toToken s,c::l)
解析器:
structure CalculatorParser : CalculatorParser = struct
open CalculatorOperation
exception CalculatorParser
datatype expr = NumNode of int
| UminusNode of expr
| MultiplyNode of expr * expr
| DivNode of expr * expr
| PlusNode of expr * expr
| MinusNode of expr * expr
| ModuloNode of expr * expr
| PowerNode of expr * expr
fun parserBrackets l = parserHelper2 l
and parserHelper l
= case l of
(Num n)::l1 => (NumNode n,l1)
| Lpar3::l1 => let val (en,l2) = parserBrackets l1 in case l2 of Rpar3::l3 => (en,l3)
| _ => raise CalculatorParser end
| Lpar2::l1 => let val (en,l2) = parserBrackets l1 in case l2 of Rpar2::l3 => (en,l3)
| _ => raise CalculatorParser end
| Lpar::l1 => let val (en,l2) = parserBrackets l1 in case l2 of Rpar::l3 => (en,l3)
| _ => raise CalculatorParser end