← 返回日报
略读 预计 1 分钟

A question about a factorial operator

摘要

一位开发者正在编写支持浮点数的汇编器,其中实现了阶乘运算符以用于泰勒级数。他发现解析器存在 bug,导致 (2 + 3)!无法正确解析。在修复过程中,他困惑于 - 3! 应如何解析:是报错(因为负数阶乘未定义),还是解析为 -(3!) 得到 - 6?他询问负号与阶乘的优先级问题。

荐读理由

这个提问涉及运算符优先级和解析器设计的具体决策,如果你在写自己的语言或解析器,可以借鉴其讨论思路;但内容本身没有给出答案,只是抛出了问题,需要进一步阅读评论才能获得可迁移的结论。

原文

I wrote an assembler that supports floating point values. One of the operators I implemented was factorial because a lot of Taylor series seem to use it to define various constants. So right now, I have .float -((2*3.14159265)**11)/11! I found a bug in the parsing such that (2+3)! doesn't parse (the parsing of the factorial operator is in the wrong location). In fixing the bug, I found an issue that I don't know how best to resolve, since I personally have never used a programming language that defined a factorial operator. So my question: what should -3! produce? Should it error out as factorial isn't defined for negative numbers? Or should it parse as -(3!) and return -6? I ask because of -(2+3)!. What binds tighter? The minus, or the factorial?

Lobsters · 提问/讨论 · 3 赞 · 2 评 阅读原文 →

这条对你有帮助吗?