为什么 Data.Text 的示例对我无效?

9

以下是我在ghci中尝试的操作:

import Data.Text
strip "  abc  "

我收到了这个错误信息:
<interactive>:1:6:
    Couldn't match expected type `Text' against inferred type `[Char]'
    In the first argument of `strip', namely `"  abc  "'
    In the expression: strip "  abc  "
    In the definition of `it': it = strip "  abc  "

我本以为这个方法会有效,因为它在很多网页上都有提到,包括这篇答案:在Haskell中,如何从字符串的开头和结尾去除空格?

我哪里做错了吗?

3个回答

16

为了将字符串字面量作为 Text 值使用,您需要启用过载的字符串字面量(否则字符串字面量将始终具有类型String = [Char])。

如果没有过载的字符串字面量,您将不得不使用 packString 转换成 Text,因此:

strip $ pack "  abc  "

6
最简单的启用过载字符串的方法是在您的 .hs 文件的第一行添加 pragma:{-# LANGUAGE OverloadedStrings #-} - Thomas M. DuBuisson

11

你应该使用 ghci -XOverloadedStrings 命令来启动ghci,或者,如果你已经在ghci中并且不想退出,可以使用 :set -XOverloadedStrings 命令来动态设置标志。


0
{-# OPTIONS_GHC -fwarn-missing-signatures #-}
{-# LANGUAGE OverloadedStrings #-}

import Data.Text as MJ

main :: IO()
main = do

      print $ strip $ pack "  abc  "
      print  $ MJ.intercalate "as" ["1","2","3"]

我会尝试改进我的格式 - 上面是一个使用ghc选项标识为{-# text #-}的工作.hs文件的示例。 - matrixmike

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接