Reputation: 632
In the documentation of Data.Text, there are examples such as replace "oo" "foo" "oo"
. However, when I try to run this, it tells me that the function replace was expecting Text, but got String. Now, of course, I could use pack
in front of every constant to turn the Strings into type Text, but that is rather inconvenient. Is there a way to write text constants the way they do in the documentation?
Upvotes: 3
Views: 484
Reputation: 476503
The documentation of Data.Text
has for all examples the OverloadedStrings
extension enabled. This will, for all string literals, add an implicit fromString
function call.
For example:
$ ghci -XOverloadedStrings
GHCi, version 8.0.2: http://www.haskell.org/ghc/ :? for help
Loaded GHCi configuration from /home/kommusoft/.ghc/ghci.conf
Prelude> import Data.Text
Prelude Data.Text> replace "oo" "foo" "oo"
"foo"
or you can add this as a pragma in your Haskell file:
{-# LANGUAGE OverloadedStrings #-}
import Data.Text
foo = replace "oo" "foo" "oo"
By using OverloadedString
s you can make your own type that works with string literals. For example you can make a type:
import Data.String
newtype SpecialString = SpecialString String
instance IsString SpecialString where
fromString = SpecialString
Now you can use string literal, and these can, depending on the context, get converted to a SpecialString
.
Upvotes: 10
Reputation: 18249
I checked the documentation and you're right - this will only work if you are using the OverloadedStrings GHC extension.
It allows you to use string literals for other "string-like" types, and is pretty much a necessity if you're working heavily with Text
or ByteString
. I am surprised that it does not appear to be mentioned in the documentation, but it is clearly assumed that OverloadedStrings
is in use in these examples.
Upvotes: 2