Now that we’ve discussed defining your own typeclasses and
making your types instances of typeclasses, it’s time to introduce you
to typeclasses that are a standard part of the Haskell Prelude
. As we
mentioned at the beginning of this chapter, typeclasses are at the core
of some important aspects of the language. We’ll cover the most common
ones here. For more details, the Haskell library reference is a good
resource. It will give you a description of the typeclasses and usually
also will tell you which functions you must implement to have a complete
definition.
The Show
typeclass is used to convert values to String
s. It is perhaps most commonly used to
convert numbers to String
s, but it
is defined for so many types that it can be used to convert quite a
bit more. If you have defined your own types, making them instances of
Show
will make it easy to display
them in ghci or print them out in
programs.
The most important function of Show
is show
. It takes one argument—the data to
convert. It returns a String
representing that data. ghci
reports the type of show
like
this:
ghci>
:type show
show :: (Show a) => a -> String
Let’s look at some examples of converting values to strings:
ghci>
show 1
"1"ghci>
show [1, 2, 3]
"[1,2,3]"ghci>
show (1, 2)
"(1,2)"
Remember that ghci displays results as they would be
entered into a Haskell program. So the expression show 1
returns a single-character string
containing the digit 1
. That is, the quotes are not part of ...
No credit card required