What are the differences between typeclasses and Abstract Data Types?
I realize this is a basic thing for Haskell programmers, but I come from a Scala background, and wo
The difference between a type class and an ADT is:
For example, consider the print
function:
print :: (Show a) => a -> IO ()
Types are static and cannot change throughout the lifetime of a program, therefore when you use a type class the method you use is chosen statically at compile time based on the inferred type at the call site. So in this example I know that I am using the Char
instance for Show
without even running the program:
main = print 'C'
ADTs let you change a function's behavior dynamically. For example, I could define:
print2 :: Either Char String -> IO ()
print2 (Left c ) = putStrLn [c]
print2 (Right str) = putStrLn str
Now, if I call print2
in some context:
print2 e
... I can't know which branch the print2
takes unless I know the runtime value of e
. If the e
is a Left
then I take the Left
branch and if e
is a Right
then I take the Right
branch. Sometimes I can statically reason about which constructor e
will be, but sometimes I cannot, such as in the following example:
main = do
e <- readLn -- Did I get a 'Left' or 'Right'?
print2 e -- Who knows until I run the program