Haskell中的字母绑定

nvbavucw  于 2022-12-29  发布在  其他
关注(0)|答案(1)|浏览(158)

我想打印以下输出。

  1. import Data.Char
  2. main = do
  3. output = map toUpper "helloworld"
  4. putStrLn output

失败并显示错误消息。

  1. test.hs:4:12: error:
  2. parse error on input ‘=’
  3. Suggested fix:
  4. Perhaps you need a 'let' in a 'do' block?
  5. e.g. 'let x = 5' instead of 'x = 5'
  6. |
  7. 4 | output = map toUpper "helloworld"
  8. |

但是,如果我使用let绑定,它就起作用了,为什么?

  1. main = do
  2. -- it works
  3. let output = map toUpper "helloworld"
  4. putStrLn output
t0ybt7op

t0ybt7op1#

do内部,语法确实要求使用let variable = expression,正如错误消息所暗示的那样,关于语法选择没有太多要说的。
有人可能会问,为什么没有选择variable = expression(没有let)作为正确的语法,很难猜测其基本原理,但请注意

  1. foo = do
  2. let x1 = e1
  3. let x2 = e2
  4. ...

以及

  1. foo = do
  2. let x1 = e1
  3. x2 = e2
  4. ...

both valid。主要区别在于后者允许e1e2都引用x1x2,这对于相互递归定义很有用。相比之下,在前者中,块e1不能引用x2
关键在于,在let之后,可以写出一个定义方程块,而不仅仅是一个。
无论如何,上面解释的区别在实践中并不重要,因为我们并不经常使用相互递归。

展开查看全部

相关问题