tags:

views:

150

answers:

3

I am new to Haskell and this mixture of Infix and Prefix notation is confusing me. What is the difference between an operator like '+' and a function like head? How do I write an operator 'c' which does this 1 c 1 = 2?

I found this definition a ! b = True. How does Haskell know that I am defining ! and not a function a?

+13  A: 

In Haskell, to create an operator you must use the following "operator symbols":

! # $ % * + . / < = > ? \ ^ | : - ~

So, for example

($$$) a b = a+b

Defines an operator $$$ which can be used in the expression 1 $$$ 1 to yield a value of 2.

Conceptually, there is no difference between an operator and a function, and you can use backticks or parens to make one work like the other.

EDIT:

Just so it is 100% clear, let me demonstrate turning a function into an operator and vice versa:

For the operator '+', the following two expressions are equivalent:

1+1
(+) 1 1

Similarly, for a function, the following two expressions are equivalent:

foo 1 2
1 `foo` 2
jgg
You can also define operators and functions using infix syntax too. `a $$$ b = a + b` and `a `foo``` b = a + b` both work as definitions for example. (Ack! There shouldn't be a space after foo and the following backquote.)
trinithis
trinithis: Yep, you're right. I thought about that but forgot to mention it.
jgg
+5  A: 

Haskell knows you aren't defining a function called a because the ! wouldn't be valid in a function argument list. In order to use the ! not as an operator but just as a normal identifier, you need to enclose it in parentheses. If you wrote instead a (!) b = True, then it would define the function a :: t -> t1 -> Bool.

This is the entire difference between operators and normal identifiers in Haskell — there are special syntax rules for operators that allow them to be used infix without backticks. Otherwise, they're just functions.

Chuck
+5  A: 

Really, the only difference is syntax. Function names begin with a lower-case letter, followed by a series of alpha-numeric characters. Operators are some unique sequence of the typical operator characters (+ - / * < > etc.).

Functions can be used as operators (in-fix) by enclosing the function name in ` characters. For example:

b = x `elem` xs -- b is True if x is an element in xs.

Operators can be used as functions (pre-fix) by enclosing the operator in parens. For example:

n = (+) 2 5 -- n = 2 + 5, or 7.
Daniel Pratt