如何通过Haskell中的列表理解正确生成String列表?

chr*_*tic 2 string haskell list char

我需要使用列表理解来生成这样的列表:[“ AaBB”,“ AbBB”,“ AcBB”,​​“ AdBB”,“ AeBB”,“ AfBB”,“ AgBB”]。但是我一直在创建表达式来解决这个问题

我尝试创建一个列表,其中每个元素都是字符串连接,类似“ A” + x +“ BB”,其中x是从“ a”开始到“ g”结束的一系列字母中的元素

module C where
    genList :: [String]
    genList = [ "A" ++ x ++ "BB" | x <- ["a" .. "g"]] 
Run Code Online (Sandbox Code Playgroud)

因此,我期望生成一个与问题中所要求清单相似的清单。但是相反,我只是遇到了此编译错误:

Prelude> :l exC
[1 of 1] Compiling C                ( exC.hs, interpreted )

exC.hs:3:41: error:
    • No instance for (Enum [Char])
        arising from the arithmetic sequence ‘"a" .. "g"’
    • In the expression: ["a" .. "g"]
      In a stmt of a list comprehension: x <- ["a" .. "g"]
      In the expression: ["A" ++ x ++ "BB" | x <- ["a" .. "g"]]
  |
3 |     genList = [ "A" ++ x ++ "BB" | x <- ["a" .. "g"]] 
  |                                         ^^^^^^^^^^^^
Failed, no modules loaded.
Run Code Online (Sandbox Code Playgroud)

Jos*_*ica 5

您不能使用..语法来构建字符串列表。幸运的是,您在这里将其用于单字符字符串,因此您可以仅使用它来构建字符列表:[ "A" ++ x : "BB" | x <- ['a' .. 'g']]

  • 对此进行扩展(我刚刚开始回答自己的问题,现在已经很多余了,但是我认为这对OP可能有所帮助):如错误消息所示,`..语法仅针对[枚举](https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#t:Enum)类型类。具体来说,它是[enumFromTo](https://hackage.haskell.org/package/base-4.12.0.0/docs/Prelude.html#v:enumFromTo)函数的语法糖。还有一个很好的理由说明为什么`Char`是`Enum`的实例,而`String`不是。您说“ hello”之后的“ next”字符串是什么? (3认同)