Home > Software engineering >  Assign show function functionality to another keyword
Assign show function functionality to another keyword

Time:11-02

data Sentence = S String

instance Show Sentence where
         show (S p) = p

For input

show (S "y")

Output is

"y"

What should I add to my code that I get the same result but instead of using keyword "show" I use "print?

print (S "y")
"y"

CodePudding user response:

show is not a keyword. It's an identifier. It identifies a function.

In order to use print instead of it, just tell the compiler that you want the identifier print to identify the same function as show:

print = show

If you want to add a type signature to it (you don't have to, but it's a good practice), that signature will have to include the Show constraint, because that's whence the function show comes:

print :: Show a => a -> String
print = show

Alternatively, if you wanted the function print to only apply to type Sentence (rather than any showable type), you can make your type signature specify that:

print :: Sentence -> String
print = show

In this case the Show constraint isn't necessary, because the compiler knows the type and can lookup the Show instance for it.

  • Related