我想从输入中解析跳过 Forth 风格的 if,Forth 风格意味着每个 if 都以 开头if
和结尾then
,假设所有输入都是正确的,不需要处理不匹配。
问题是每个部分都if
可以递归地包含任意数量的 other if
。
这是我对测试用例的最佳解决方案:
Red []
skip-nested-ifs: [skip to ['if | 'then] skip-nested-ifs-helper]
skip-nested-ifs-helper: ['then | skip-nested-ifs skip-nested-ifs-helper ]
rules: skip-nested-ifs
test-cases: [
[if a then]
[if a else b then]
[if a if b then then]
[if a if b then 5 then]
[if a if b then 5 if c then then]
[if a else if b then then]
[if a else if b then 5 then]
[if a else if b then if c then then]
[if a if b if c then if d then then then]
]
forall test-cases [
prin [mold test-cases/1 ""]
print either parse test-cases/1 rules [ "OK" ] [ "FAIL" ]
]
输出是:
[if a then] OK
[if a else b then] OK
[if a if b then then] OK
[if a if b then 5 then] FAIL
[if a if b then 5 if c then then] FAIL
[if a else if b then then] OK
[if a else if b then 5 then] FAIL
[if a else if b then if c then then] OK
[if a if b if c then if d then then then] OK
所以他们中的三个失败了,因为它们在一个和另一个5
之间包含了一些东西(在这种情况下) 。then
可能修复非常简单和明显,但我现在看不到它。如果可能的话,你能帮我解决上面的规则,或者显示一个通过所有测试的不同规则吗?