我如何正确使用另一个模块中声明的列表

我遇到了错误:

> Levels.hs:3:40: error:
    parse error (possibly incorrect indentation or mismatched brackets)
  |
3 | let screens = ["stage one","stage two"]
  |                                        ^

when I try to use a list I declared in a module called Levels. Below is my main.hs file:

import System.IO
import Levels

main = do  
    putStrLn (head Levels.screens)

以下是我的Levels.hs

module Levels where

let screens = ["stage one","stage two"]

请问为什么我会收到此错误?

评论
  • 余温,散尽
    余温,散尽 回复

    let is only for declaring variables within some scope – the scope of a function or a monadic block. Basically what it does is, it creates a new top-level environment in which you can then declare variables.

    But when writing a source file, you're already at the top level, so you don't need to (and in fact, can't) use let.

    像这样写出来

    module Levels where
    
    screens = ["stage one","stage two"]
    

    ...最好还添加一个类型签名

    screens :: [String]
    

    Where you could use let is if you needed some helper definitions for implementing that list, like

    screens = let stage1 = "stage one"
                  stage2 = "stage two"
              in [stage1, stage2]
    

    或者,就像通常写的那样,

    screens = [stage1, stage2]
     where stage1 = "stage one"
           stage2 = "stage two"
    

    Note that when using let in GHCi, like

    Prelude> let screens = ["stage one","stage two"]
    Prelude> screens
    ["stage one","stage two"]
    

    you're already in a scope, namely an implicit do block of the IO monad, i.e. this is like

    main :: IO ()
    main = do
       let screens = ["stage one","stage two"]
       putStrLn $ head screens