Trajanson
Trajanson

Reputation: 441

$ Dollar Sign Not Allowed in Place of Parentheses

Replacing the parentheses in this function:

isInteger x = x == fromInteger (round x)

with a dollar sign operator:

isInteger x = x == fromInteger $ round x

raises an error.

What are the limitations of using the $ operator?

Upvotes: 0

Views: 305

Answers (2)

chepner
chepner

Reputation: 531948

$ has extremely low precedence, lower than ==, lower than everything. Your attempt is parsed as

isInteger x = (x == fromInteger) $ (round x)

that is, it attempts to apply a Bool as a function. You could write

isInteger x = x == (fromInteger $ round x)

but that doesn't really save any parentheses; it just shifts them.


If you really want to get rid of the parentheses (or at least, really move them aside), you can take advantage of the fact that (-> r) is an applicative functor, which in brief means that f <*> g == \x -> f x (g x). Replacing f with (==) and g with fromInteger . round, you get

isInteger = (==) <*> fromInteger . round

because

x == fromInteger (round x) -> (==) x (fromInteger (round x))
                           -> (==) x ((fromInteger . round) x)
                              ----    ---------------------
                               f   x (          g           x)

Upvotes: 6

Kapol
Kapol

Reputation: 6463

This is the beginning of the accepted answer in the question you linked in the comment:

The $ operator is for avoiding parentheses. Anything appearing after it will take precedence over anything that comes before.

Taking this into account, isInteger x = x == fromInteger $ round x becomes isInteger x = (x == fromInteger) (round x), so you're taking the result of x == fromInteger (which is of type Bool) and applying it to round x. This clearly doesn't make sense.

Upvotes: 1

Related Questions