Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

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]?

like image 958
Janez Lukan Avatar asked Jun 18 '16 08:06

Janez Lukan


2 Answers

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.

like image 183
stholzm Avatar answered Nov 11 '22 10:11

stholzm


In my case I had code that was doing concatenation of a String and Text value:

"cd " ++ stackProjectLocation

"cd " was being of type Text because of using {-# LANGUAGE OverloadedStrings #-}

And stackProjectLocation was a String

The solution was to use (<>) :: Semigroup a => a -> a -> a:

"cd " <> stackProjectLocation
like image 37
Răzvan Flavius Panda Avatar answered Nov 11 '22 12:11

Răzvan Flavius Panda