为什么Data.Text示例不适合我?

Eri*_*and 9 haskell

这是我在ghci中尝试做的事情:

import Data.Text
strip "  abc  "
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息:

<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  "
Run Code Online (Sandbox Code Playgroud)

我期待这个工作,因为它是在许多网页上给出的,包括这个答案:在Haskell中,你如何从字符串的开头和结尾修剪空格?

我究竟做错了什么?

sep*_*p2k 16

您需要启用重载的字符串文字才能将字符串文字用作Text值(否则字符串文字将始终具有该类型String = [Char]).

没有重载的字符串文字,你将不得不pack用来创建Texta String,所以:

strip $ pack "  abc  "
Run Code Online (Sandbox Code Playgroud)

  • 通过将pragma添加到.hs文件的第一行,最容易启用重载字符串:`{ - #LANGUAGE OverloadedStrings# - }` (6认同)

Dan*_*ner 11

您应该使用或者启动ghci ghci -XOverloadedStrings,如果您已经在ghci中并且不想退出,请使用动态设置标志:set -XOverloadedStrings.