Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

haskell - Couldn't match expected type `Text' with actual type `[Char]'

This might be a really noobish question, but I can't get past this problem (as I just started learning Haskell).

I have a simple block of code:

module SomeTest where
import Data.Text

str =  replace "ofo" "bar" "ofofo"

If I call this with str, I get:

<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"

I don't know why I'm getting this error and how to get pass it. Isn't Text just a synonym for [Char]?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately, Haskell has several conflicting types for strings of characters. String literals are usually of type String which is just an alias for [Char]. Because that is an inefficient representation of strings, there are alternatives, like Text.

In your case, adding {-# LANGUAGE OverloadedStrings #-} as the first line of your program will make it compile. Basically your string literals can be of type Text then.

In the case of ghci you can run :set -XOverloadedStrings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...