无法将预期类型"文本"与实际类型"[Char]"匹配

Jan*_*kan 16 haskell

这可能是一个非常愚蠢的问题,但我无法解决这个问题(因为我刚开始学习Haskell).

我有一个简单的代码块:

module SomeTest where
import Data.Text

str =  replace "ofo" "bar" "ofofo"
Run Code Online (Sandbox Code Playgroud)

如果我打电话给str我,我得到:

<interactive>:108:19: error:
* Couldn't match expected type `Text' with actual type `[Char]'
* In the first argument of `Data.Text.replace', namely `"ofo"'
  In the expression: Data.Text.replace "ofo" "bar" "ofofo"
  In an equation for `it': it = Data.Text.replace "ofo" "bar" "ofofo"

<interactive>:108:25: error:
* Couldn't match expected type `Text' with actual type `[Char]'
* In the second argument of `Data.Text.replace', namely `"bar"'
  In the expression: Data.Text.replace "ofo" "bar" "ofofo"
  In an equation for `it': it = Data.Text.replace "ofo" "bar" "ofofo"

<interactive>:108:31: error:
* Couldn't match expected type `Text' with actual type `[Char]'
* In the third argument of `Data.Text.replace', namely `"ofofo"'
  In the expression: Data.Text.replace "ofo" "bar" "ofofo"
  In an equation for `it': it = Data.Text.replace "ofo" "bar" "ofofo"
Run Code Online (Sandbox Code Playgroud)

我不知道为什么我得到这个错误以及如何通过它.不Text只是一个同义词[Char]吗?

sth*_*lzm 28

不幸的是,Haskell对于字符串有几种冲突的类型.字符串文字通常String是只是别名的类型[Char].因为这是字符串的低效表示,所以有其他选择,例如Text.

在您的情况下,添加{-# LANGUAGE OverloadedStrings #-}作为程序的第一行将使其编译.基本上你的字符串文字可以是类型Text.

  • `OverloadedStrings`隐式将所有字符串文字`"foo"`变成`fromString"foo"`.[`fromString`](http://hackage.haskell.org/package/base-4.9.0.0/docs/Data-String.html#v:fromString)是一个可以从`String`转换为任何实例的方法`IsString`类,例如`Text`. (19认同)
  • 虽然这会起作用,但您可能会得到更复杂的模糊类型错误,因为GHC无法确定应该使用哪个"IsString"实例.通常可以通过将"some text"更改为("some text":: Text)来解决这些问题. (7认同)