let vs regular assignment in GHCi

前端 未结 3 1074
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-05 18:58

Is there any difference between

f x = x + 1

and

let f x = x + 1

when typed into GHCi? IIUC, there\'s a sp

相关标签:
3条回答
  • 2021-01-05 19:48

    Another difference:

    λ> x = 1 :: Int
    λ> :sprint x
    x = _
    λ> let x = 1 :: Int
    λ> :sprint x
    x = 1
    
    0 讨论(0)
  • 2021-01-05 19:52

    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.

    0 讨论(0)
  • 2021-01-05 19:55

    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.

    0 讨论(0)
提交回复
热议问题