[Haskell] Haskell implementation of infixr and infixl/priorities

Ben Rudiak-Gould Benjamin.Rudiak-Gould at cl.cam.ac.uk
Fri Oct 22 12:58:36 EDT 2004

Peter Theissen wrote:

>  I´m progarmming a parser for functional programs. Now I want to
>  implement the infixL and infixR feature to increase the readability
>  of the code. I would be very glad if anyone can send me some
>  information about the implementation of this feature of the Haskell
>  parser or where I can find something about it.

Different Haskell implementations may differ, but I think the easiest 
way to handle this is to have your parser treat all infix operators as 
though they had the same precedence and associativity, and then go back 
and fix up the infix expressions later. Otherwise you have to search for 
infix directives before you've finished parsing, which is probably a bad 
idea. The fix-up process can be done in two passes: first parenthesize 
things according to their precedence, and then according to their 
associativity. If you're not familiar with the algorithms for the first 
pass, try to find a hand-coded parser for arithmetic expressions.

>  Futher qurestion: Is it possible to define priorities for functions
>  in Haskell? Any hints about that?

If you mean use the infix* directives with ordinary function names like 
"foo", then yes, it's perfectly okay to write

    infixr 3 `foo`

The difference between functions and infix operators is only lexical. 
Your lexer should recognize "+" as infix (+) and "`foo`" as infix foo. 
These two cases shouldn't need to be treated separately except in the lexer.

-- Ben

More information about the Haskell mailing list