blue-sky
blue-sky

Reputation: 53896

Can | be used as part of variable name?

This code causes compiler error :

Prelude> let probBorA = 3
probBorA :: Num a => a
Prelude> let probB|A = 3

<interactive>:25:11: Not in scope: data constructor ‘A’
Prelude> 

| cannot be used as part of a variable name in Haskell ?

Upvotes: 0

Views: 110

Answers (1)

David Young
David Young

Reputation: 10793

It cannot be part of a name that contains alphanumeric characters, as in your example. Names of bindings that are not infix operators must contain only alphanumeric characters, single quotes and underscores. There are further restrictions on what may start with an uppercase letter or lowercase letter and a couple minor restrictions on where single quotes can appear. A name can also not start with a number.

The particular character | has special meaning because it is the syntax for guards. Your example would be the same as:

Prelude> let prob | A = 3

For more details, see the link Eric provided in the comments.

camelCase is the recommended (and, by a very large margin, the most prevalent) naming convention, but you could also name things like_this or even'like'this.

The ' (single quote) is most often used at the end of a variable name, usually to indicate that it is a modified version of the binding without the single quote. For instance, you might have

ghci> :{
   |> let x   = 3
   |>     x'  = x + 1
   |>     x'' = x' * 2
   |> in (x, x', x'') 
   |> :}
(3,4,8)

It is possible to make new operators (with new names) in Haskell like this:

ghci> let a .|. b = a + b
ghci> 2 .|. 2
4

Or even, if you really wanted to:

ghci> let a !@#$%^&* b = a - b
ghci> 7 !@#$%^&* 4
3

(Usually you try to use operator names that are far more clear though)

but, as I said, | by itself has special significance.

Upvotes: 6

Related Questions