我正在用 F# 编写一个简单的表达式解析器,对于每个运算符,我只想支持一定数量的操作数(例如,两个用于 Modulo,三个用于 If)。这是我所拥有的:
type Operator =
| Modulo
| Equals
| If
let processOperator operands operator =
match operator with
| Modulo ->
match operands with
| [ a:string; b:string ] -> (Convert.ToInt32(a) % Convert.ToInt32(b)).ToString()
| _ -> failwith "wrong number of operands"
| Equals ->
match operands with
| [ a; b ] -> (a = b).ToString()
| _ -> failwith "wrong operands"
| If ->
match operands with
| [ a; b; c ] -> (if Convert.ToBoolean(a) then b else c).ToString()
| _ -> failwith "wrong operands"
我想摆脱或简化内部列表匹配。实现这一目标的最佳方法是什么?我应该使用多个警卫吗?