Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$ operator in Haskell gives data constructor error

Tags:

haskell

1:([2]) works as expected.

1:$[2] gives <interactive>:15:2: Not in scope: data constructor `:$'

I thought the $ operator parenthesizes everything after it: Haskell: difference between . (dot) and $ (dollar sign)

What is going on?

like image 950
ssh Avatar asked Nov 28 '22 01:11

ssh


2 Answers

You put $ between a function and a value, and it applies the function to the value.

1: isn't a function, but (1:) is, so you can do (1:) $ [2] but not 1: $ [2].

(The error you got was because without spaces, the compiler thinks :$ is one thing, not two, and operators starting with : are data constructors, just like functions starting with capitals are data constructors.)

like image 164
AndrewC Avatar answered Dec 10 '22 13:12

AndrewC


The $ operator is not syntax, it's just a normal function like every other. When you write

1 :$ [2]

The first problem the compiler sees is that :$ appears as its own operator (consider + + versus ++, these are very different things), but :$ is not defined anywhere.

If you were to write

1 : $ [2]

Then the compiler doesn't understand what to do since you have two operators right next to each other, this isn't allowed, just as 1 + * 2 isn't allowed. These expressions simply don't make any sense. The $ operator is actually just defined as

f $ x = f x

But it has a low precedence, like Please Excuse My Dear Aunt Sally for arithmetic operator precedence, so that you can chain operations more easily. It does not actually insert parentheses into an expression.

like image 29
bheklilr Avatar answered Dec 10 '22 13:12

bheklilr