mb14
mb14

Reputation: 22596

How to work with Regex and OverloadedString

I have been using Text.Regex.Posix in a file, everything works fine so far. Now, I would like to use OverloadedStrings for something else but in the same file. The problem is when I activate OverloadedString all the code related to regex doesn't compile because the strings becomes ambiguous.

Is there a way to deal with this without having to add type signature to every strings or deactivate OverloadedStrings ?

Upvotes: 1

Views: 158

Answers (1)

bheklilr
bheklilr

Reputation: 54058

I see two approaches here. You can do some import shuffling and just alias the functions you need to have less general types, such as

import qualified Text.Regex.Posix as P
import Text.Regex.Posix hiding ((=~))

(=~) :: RegexContext Regex String target => String -> String -> target
(=~) = (P.=~)

Then you don't have to change the code throughout your file. This can lead to confusion though, and it requires FlexibleContexts to work (not a big deal).

Alternatively you can create your own Python-like syntax for specifying the type:

r :: String -> String
r = id

u :: Text -> Text
u = id

b :: ByteString -> ByteString
b = id

example :: Bool
example = r"test" =~ r"te.t"

splitComma :: Text -> Text
splitComma = Data.Text.splitOn (u",")

But this will require you to edit more of your code. It doesn't use any extra language extensions and the code to implement it is very simple, even in comparison to the first method. It Also means that you'll have to use parentheses or $ signs more carefully, but you can also use the r, u, and b functions as, well, functions.

Upvotes: 3

Related Questions