Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `2 + x = 7` valid Haskell?

Tags:

haskell

When I try to compile

main = putStrLn $ show x where     2 + x = 7 

GHC complains

error: Variable not in scope: x   | 1 | main = putStrLn $ show x   |                        ^ 

So it seems that 2 + x = 7 is by itself syntactically valid, although it doesn't actually define x. But why is it so?

like image 801
fghzxm Avatar asked May 06 '18 13:05

fghzxm


People also ask

What does <$> mean in Haskell?

It's merely an infix synonym for fmap , so you can write e.g. Prelude> (*2) <$> [1.. 3] [2,4,6] Prelude> show <$> Just 11 Just "11" Like most infix functions, it is not built-in syntax, just a function definition. But functors are such a fundamental tool that <$> is found pretty much everywhere.

What does ++ do Haskell?

The ++ operator is the list concatenation operator which takes two lists as operands and "combine" them into a single list.

What is -> in Haskell?

(->) is often called the "function arrow" or "function type constructor", and while it does have some special syntax, there's not that much special about it. It's essentially an infix type operator. Give it two types, and it gives you the type of functions between those types.

Can Haskell lists have different types?

Haskell also incorporates polymorphic types---types that are universally quantified in some way over all types. Polymorphic type expressions essentially describe families of types. For example, (forall a)[a] is the family of types consisting of, for every type a, the type of lists of a.


1 Answers

It is valid because it defines + instead.

main = print (3 + 4)    where -- silly redefinition of `+` follows    0 + y = y    x + y = x * ((x-1) + y) 

Above, the Prelude (+) function is shadowed by a local binding. The result will be 24, not 7, consequently.

Turning on warnings should point out the dangerous shadowing.

<interactive>:11:6: warning: [-Wname-shadowing]     This binding for ‘+’ shadows the existing binding 
like image 63
chi Avatar answered Sep 28 '22 00:09

chi