You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell报错‘Last generator in do {...} must be an expression’原因及解决求助

Fixing the "Last generator in do {...} must be an expression" Error in Haskell

Hey there! I totally get how confusing this error can be when you're just starting out with Haskell. Let's break down what's going wrong and fix your code quickly.

The Root Cause

Haskell's do notation requires each statement in the block to be clearly separated—either by a newline or a semicolon. In your original code, you squeezed multiple statements onto the same line without any separators:

main = do putStrLn "What is your name?" name <- getLine putStrLn ("Name of customer is "++ name)

The compiler can't tell where one statement ends and the next begins, so it misinterprets the structure. It thinks name <- getLine is the last generator (binding) in the do block, but there's still code after it—hence the error message.

The Fixed Code

Here's the corrected version using newlines (this is the standard, most readable way to write do blocks):

main = do
  putStrLn "What is your name?"
  name <- getLine
  putStrLn ("Name of customer is " ++ name)

If you really want to keep everything on one line (not recommended for readability), you can use semicolons to separate the statements:

main = do putStrLn "What is your name?"; name <- getLine; putStrLn ("Name of customer is " ++ name)

Quick Explanation

Each line (or semicolon-separated part) in the do block is a distinct step:

  • First, we print the prompt with putStrLn
  • Then we bind the input from getLine to the variable name
  • Finally, we print the greeting using the name variable

By separating these steps clearly, the compiler understands the structure of your do block and the error goes away.

内容的提问来源于stack exchange,提问作者Rahat Batool

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:00:53