Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

let vs regular assignment in GHCi

Tags:

haskell

Is there any difference between

f x = x + 1

and

let f x = x + 1

when typed into GHCi? IIUC, there's a special rule that let without in inside GHCi effectively applies to the entire scope of the interpreter. But if the presence of let makes no difference, what's the point of this rule?

Edit: using GHCi version 8.0.2.

like image 541
max Avatar asked Mar 23 '17 23:03

max


People also ask

What is the recommended basis for The GHCi file?

The following is the recommended basis for the .ghci file: -- Turn off output for resource usage and types.

When will September 2022 let room assignments be posted?

MANILA, Philippines – The September 2022 LET Room Assignments are expected to be posted by the Professional Regulation Commission Board of Professional Teachers few weeks before the exams.

What are the spaces in a variable assignment?

Under a normal variable assignment instance, no spaces can exist. For both the assignment operator ‘=’ and any binary operator, it is mandatory to keep a structure with operator and operands syntactically attached. While for typical variable declarations any in-between spare spaces break the assignment:


3 Answers

No, there's no difference.

It used to be that ghci was essentially an open-ended IO do block. But the inability to define new types in this syntax form, and the need to write let for every definition, were seen as annoying restrictions that often got in the way of everyday interactive use, and so the syntax of ghci has slowly become more permissive. But it is just a syntax change -- nothing deep.

However, there is one thing to be aware of: if you want to start a block, you must do that explicitly. For example,

> f [] = 3
> f (x:xs) = 4

is equivalent to

> let f [] = 3
> let f (x:xs) = 4

and not

> :{
| let f [] = 3
|     f (x:xs) = 4
| :}

hence will be a new definition of f that shadows the old one and is only defined on non-empty lists, whereas you probably meant to give two equations for a single f. With automatic block mode (:set +m), ghci can notice that let started a block and automatically give you the latter when you type let, thus:

> let f [] = 3
|     f (x:xs) = 4
|

It will not do this for short-form (non-let) definitions.

like image 200
Daniel Wagner Avatar answered Oct 11 '22 13:10

Daniel Wagner


Although this question was asked months ago, I do notice some more difference when I start to learn Haskell recently.

> :set -Wall
> a = 2
> let a = 3

results in a warning about name shadowing (-Wname-shadowing), while

> :set -Wall
> a = 2
> a = 3

does not. It seems that the warning only checks for explicitly written let statements.

like image 20
Weijun Zhou Avatar answered Oct 11 '22 12:10

Weijun Zhou


Another difference:

λ> x = 1 :: Int
λ> :sprint x
x = _
λ> let x = 1 :: Int
λ> :sprint x
x = 1
like image 2
Michiel Borkent Avatar answered Oct 11 '22 13:10

Michiel Borkent