Haskell Default Methods
A default method is an implementation written inside the class itself. An instance can keep that implementation or replace it with its own.
An instance can keep the default
Label gives a default label. The Box instance defines nothing and still gets it.
class Label a where
label :: a -> String
label _ = "thing"
data Box = Box
instance Label Box
main :: IO ()
main = print (label Box)An instance can replace the default
Star defines its own label. Its print shows the replacement, not the default.
class Label a where
label :: a -> String
label _ = "thing"
data Star = Star
instance Label Star where
label _ = "star"
main :: IO ()
main = print (label Star)A default can build on a required method
doubleMeasure has a default that doubles measure. The Box instance defines only measure.
class Measurable a where
measure :: a -> Int
doubleMeasure :: a -> Int
doubleMeasure x = measure x * 2
data Box = Box Int
instance Measurable Box where
measure (Box n) = n
main :: IO ()
main = print (doubleMeasure (Box 4))Example
class Label a where
label :: a -> String
label _ = "thing"
data Plain = Plain
data Fancy = Fancy
instance Label Plain
instance Label Fancy where
label _ = "fancy"
main :: IO ()
main = do
print (label Plain)
print (label Fancy)Key points
- Default method: an implementation given in the class definition.
- Kept default: an instance that defines no replacement uses the class implementation.
- Replaced default: an instance that defines the method uses its own code instead.
- Default from another method: a default can call a required method of the same class.
- Required method: a method with no default that every instance must define.
In this example, Label gives every type the default label thing. Plain keeps that default, and Fancy replaces it with its own label. The two prints show the kept and replaced results side by side.
Note
a default keeps code in one place instead of repeating it in every instance.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What happens when an instance does not define a method that has a default?