haskellprelude.ls

How to show strings in custom Prelude library Protolude


I read this blog post on how to create a custom Prelude library. The library can be found here. One of the things it does is prohibit String. It also defines a function for automatic string conversions (here). I have enabled OverloadedStrings in the cabal file.

Before using this library I had:

data Point = Point Int Int
instance Show Point where
  show (Point x y) = "(" ++ show x ++ ", " ++ show y ++ ")"

After using the library it says: "show' is not a (visible) method of classShow'"

So I resorted to create a custom function to show the data type:

showPoint :: Point -> LText
showPoint (Point x y) = toS ("(" ++ show x ++ ", " ++ show y ++ ")")

The compiler is saying that the use of toS, "(", show is ambiguous, but I don't understand why. Do I have to do something like what is proposed here?

Edit:

Had to disable OverloadedStrings and change the code to the following:

showPoint :: Point -> LText
showPoint (Point x y) = toS "(" <> show x <> toS ", " <> show y <> toS ")"

Wondering if it is possible to do the same without disabling OverloadedStrings so I don't have to use toS for every String.


Solution

  • This is what worked for me:

    {-# LANGUAGE OverloadedStrings #-}
    
    module Test where
    
    import Protolude
    import qualified Base as PBase
    
    data P = P Int
    
    instance PBase.Show P where
      show (P x) = "a P " ++ show x
    

    Update

    The protolude implemention of show is as a normal function (see the end of Protolude.hs):

    show :: (Show a, StringConv String b) => a -> b
    show x = toS (PBase.show x)
    

    So you need a PBase.Show instance in order use protolude's show function.

    Also protolude's show can return any of the string types, so you're not forcing others to use of String by defining a PBase.show instance.

    Update #2

    You can import the typeclass show function from GHC.Show:

    {-# LANGUAGE NoImplicitPrelude #-}
    
    import Protolude
    import GHC.Show
    
    data P  = P Int
    
    instance Show P where
      show (P x) = "<-- P " ++ GHC.Show.show x ++ " -->"
    
    main = print (P 123)