[Haskell-beginners] 1=2

Thomas Hallgren hallgren at chalmers.se
Tue Dec 15 14:45:01 UTC 2020


On 2020-12-14 18:14, M Douglas McIlroy wrote:
> ghc and ghci 8.6.5 accept 1=2 at top level. It seems to have no effect.

On 2020-12-15 02:29, Francesco Ariis wrote:
> Il 14 dicembre 2020 alle 20:05 amindfv at mailbox.org ha scritto:
>> It's the same in do-blocks:
>>
>> main :: IO ()
>> main = do
>>    let 3 = 2 + 2
>>    putStrLn "Oh fiddlesticks"
> 
> What happens exactly when I type this?
> 
>     λ> "prova" = "foo"
>     λ> 'c' = 'd'
>     λ> 'c'
>     'c'

These are examples of pattern bindings, but since they don't bind any variables,
they are not very useful.

As examples of more useful pattern bindings, consider

	> (xs,ys) = splitAt 3 [1..8]
	> [1,x,y] = [1..3]

These are both examples where the value of the expression on the rhs matches the
pattern on the lhs, so you can obtain the values of the variables bound by the
pattern:

	> xs
	[1,2,3]
	> ys
	[4,5,6,7,8]
	> x
	2
	> y
	3

If the value of the expression on the rhs doesn't match the pattern on the lhs,
you get an error, but because of lazy evaluation the value of the rhs is not
computed and matched against the pattern until you use one of the variables in
the pattern:

	> [1,z,2] = [1..3]
	> z
	*** Exception: <interactive>:7:1-16: Irrefutable pattern failed for pattern [1,
z, 2]

This means that when the pattern does not contain any variables, the value of
the rhs is never computed and matched against the pattern, so even if the value
does not match the pattern, there is no error message:

	> [] = [1..3]
	> [_,_,_] = []
	> True = False
	> 1 = 2

If you turn on -Wunused-pattern-binds, you get a warning for pattern bindings
like these:

	> :set -Wunused-pattern-binds
	> True=False

	<interactive>:2:1: warning: [-Wunused-pattern-binds]
	    This pattern-binding binds no variables: True = False


Best regards,
Thomas H





More information about the Beginners mailing list