user2316602
user2316602

Reputation: 632

Data.Text constants in Haskell

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

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

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

Robin Zigmond
Robin Zigmond

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

Related Questions