Jo0o0
Jo0o0

Reputation: 531

What do show and render do in Haskell?

For example, in this code:

module Main(letters) where

import Data.List(nub)

import qualified Text.PrettyPrint.HughesPJ as PP
import Text.PrettyPrint.HughesPJ(Doc,text,int,(<>),(<+>),($+$),render)

data Prop a = 
     LetterP a
   | AndP (Prop a) (Prop a)
 deriving Eq

class PPLetter a where
  ppLetter :: a -> Doc

instance PPLetter Int where
  ppLetter a = text ("p"++show a)

instance PPLetter Char where
  ppLetter = PP.char

instance PPLetter a => PPLetter [a] where
  ppLetter = PP.hcat . (map ppLetter)

class PP a where
  pp :: a -> Doc

instance PP Bool where
  pp True = text "True"
  pp False = text "False"

parens n (term@(LetterP _)) = pp term

instance PPLetter a => PP(Prop a) where   
  pp (LetterP a) = ppLetter a
  pp (AndP x y) = PP.sep [ parens 4 x, text "/\\", parens 4 y]

instance PPLetter a => Show (Prop a) where
  show x = render (pp x)

main = do
    let p = LetterP 1
    print p

Upvotes: 0

Views: 909

Answers (1)

Don Stewart
Don Stewart

Reputation: 137947

  1. The Show class, and its method, show, convert values to Strings.

  2. The render function is part of the Text.PrettyPrint module, which converts values to prettily printed strings (e.g. with layout, indenting and nesting).

Together they are used for pretty printing

Upvotes: 4

Related Questions