Search code examples
haskellghc

How to set preference for `Text` and not `String` in Haskell


I run often in the problem that GHC interprets "some text" as String when I need Text in places where both are acceptable, only to find later the error in another use and forcing an explicit type annotation.

Is there a way to set a preference for GHC to prefer Text and not String? The question is likely the same as this one but the only answer there is very heavy and not likely usable for me. Is there a better one?

I would like to be able to set a preference, that unqualified "some text" is of type Text to avoid the error in the following contrived example:

import Data.Text

some = "some"
text1 = "text1":: Text 

two = Data.Text.concat [some, text1]

Solution

  • You can put a default declaration at the top of the module so that Text will be defaulted for any ambiguous IsString values.

    default (Integer, Double, Text)
    

    In your code, the type is not ambiguous because you specified a Text-only function. The error just results from not enabling OverloadedStrings. Here is a truly ambiguous example that would benefit from a default declaration.

    {-# LANGUAGE OverloadedStrings #-}
    
    import Data.Text
    
    default (Integer, Double, Text)
    
    some = "some"
    
    main = print some
    

    Inspecting this in GHCi shows that :t some is Text. Without the default declaration, :t some is [Char] (i.e. String).