【问题标题】:How to convert a nested list of Chars to a String Haskell如何将嵌套的字符列表转换为字符串 Haskell
【发布时间】:2015-10-13 22:24:49
【问题描述】:

我有一个简单的问题,虽然Chars 的列表似乎等同于Strings,但它们的功能并不相同。如果我有一个Chars 的嵌套列表,类型为[[Char]],我想将其转换为[String],我该怎么做?

当我尝试在 [[Char]] 上执行函数并将其视为字符串时,我得到:

Couldn't match expected type `([String] -> (Int, Int, Board)) -> t'
                with actual type `[[Char]]'

当我尝试声明 type String = [[Char]] 我得到:

Ambiguous occurrence `String'
It could refer to either `Main.String', defined at Testing.hs:19:1
                      or `Prelude.String',
                         imported from `Prelude' at Testing.hs:16:1-14
                         (and originally defined in `GHC.Base')

【问题讨论】:

  • 在功能上是一样的。
  • 我试过这个,它返回StringAmbiguous
  • @anon String 已经在标准库中定义了,所以当你定义另一个String 时,GHC 不确定要使用哪个(这就是这里的错误的意思)。
  • 啊,那我该如何向编译器澄清我的意思是String
  • @anon 定义 String 并没有什么意义。字符串在概念上是字符列表,而不是字符列表列表。这也不符合您问题的第一部分(如果String[[Char]] 的同义词,那么[String] 将不是[[Char]])。在普通的标准库版本中,[String][[Char]] 已经是相同的并且可以相互互换。

标签: string list haskell char


【解决方案1】:

这两种类型完全相同,因为String[Char] 的类型同义词。 String的定义是

type String = [Char]

type 关键字表示它是类型同义词。类型同义词始终可以与其定义的类型互换。

你可以像这样在 GHCi 中看到这一点(注意 Haskell 不允许强制转换):

ghci> let test :: [Char];   test = "abc"
ghci> test :: String
"abc"
ghci> :t (test :: [Char]) :: String
(test :: [Char]) :: String :: String

【讨论】:

    【解决方案2】:

    当我尝试声明 type String = [[Char]] 时,我得到:

    Ambiguous occurrence `String'
    It could refer to either `Main.String', defined at Testing.hs:19:1
                          or `Prelude.String',
                             imported from `Prelude' at Testing.hs:16:1-14
                             (and originally defined in `GHC.Base')
    

    您收到此错误是因为您对String 的定义与base 中已定义并由Prelude 导出的定义冲突。删除您的定义并使用已经存在的定义。

    【讨论】:

      猜你喜欢
      • 2016-02-08
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 2021-02-17
      • 2021-05-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多