Prefix or infix: which is idiomatic in Haskell?

889 Views Asked by At

I am new to Haskell and do not know which is idiomatic - using operators in prefix form or infix form. From what I've noticed so far, functions with special characters for names such as <$>, <*>, >>= etc are used in infix form but functions whose names are made up of alphabets are used in prefix form. My guess is that this is inspired from mathematics, although I am not sure.

I've looked up Blow your mind, Category:Idioms and also searched up stackoverflow, but to no avail.

Edit

Clarifying, when is it idiomatic to infixify a function and prefixify an operator?

1

There are 1 best solutions below

1
Joseph Sible-Reinstate Monica On

You can call any function any way you want.

  • Regular function, prefix, nothing special: fmap foo bar
  • Regular function, infix, by adding backticks: foo `fmap` bar
  • Operator, prefix, by adding parentheses: (<$>) foo bar
  • Operator, infix, nothing special: foo <$> bar

As for what's idiomatic when calling them, that's a bit of a soft question, but here's some guidelines:

  • If you have two otherwise-identical functions, but one is an operator and the other isn't (the primary example being fmap and <$>), then use whichever one lets you use fewer parentheses.
  • If your function only has one form, then prefer the approach that doesn't require any special usage (so prefix for regular functions, and infix for operators).
  • Rather than flipping a single function to provide the second argument first, an infix operator section is often used instead. For example, (`foo` bar) is more common than flip foo bar.
  • There's a few common exceptions where regular functions are almost always used infix. For example, needle `elem` haystack is much more common than elem needle haystack. Other common ones include div and mod. I'm not aware of any of the opposite cases, though, where an operator would commonly be used as a prefix.

As for whether you should make your new function an operator or not, the answer is almost always no. Named functions are generally much easier to understand. The exceptions in this case are if it'll be something you're chaining a lot of in a single expression (like Servant's :<|> and :>), and operators that are common and well-known in the problem domain.