Any reason I couldn't create a language supporting infix, postfix, and prefix functions, and more?

前端 未结 4 1262
你的背包
你的背包 2021-02-09 23:48

I\'ve been mulling over creating a language that would be extremely well suited to creation of DSLs, by allowing definitions of functions that are infix, postfix, prefix, or eve

相关标签:
4条回答
  • 2021-02-10 00:27

    This is not too hard to do. You'll want to assign each operator a fixity (infix, prefix, or postfix) and a precedence. Make the precedence a real number; you'll thank me later. Operators of higher precedence bind more tightly than operators of lower precedence; at equal levels of precedence, you can require disambiguation with parentheses, but you'll probably prefer to permit some operators to be associative so you can write

    x + y + z
    

    without parentheses. Once you have a fixity, a precedence, and an associativity for each operator, you'll want to write an operator-precedence parser. This kind of parser is fairly simply to write; it scans tokens from left to right and uses one auxiliary stack. There is an explanation in the dragon book but I have never found it very clear, in part because the dragon book describes a very general case of operator-precedence parsing. But I don't think you'll find it difficult.

    Another case you'll want to be careful of is when you have

    prefix (e) postfix
    

    where prefix and postfix have the same precedence. This case also requires parentheses for disambiguation.

    My paper Unparsing Expressions with Prefix and Postfix Operators has an example parser in the back, and you can download the code, but it's written in ML, so its workings may not be obvious to the amateur. But the whole business of fixity and so on is explained in great detail.

    0 讨论(0)
  • 2021-02-10 00:31

    What are you going to do about order of operations?

    a * b squared
    
    0 讨论(0)
  • 2021-02-10 00:31

    You might want to check out Scala which has a kind of unique approach to operators and methods.

    0 讨论(0)
  • 2021-02-10 00:34

    Haskell has just what you're looking for.

    0 讨论(0)
提交回复
热议问题