Scala: difference between a typeclass and an ADT?

前端 未结 3 1443
孤街浪徒
孤街浪徒 2021-01-30 04:38

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

3条回答
  •  执念已碎
    2021-01-30 05:14

    The difference between a type class and an ADT is:

    • Use type classes when you want to dispatch a method based off of something's type
    • Use ADTs when you want to dispatch a method based off of something's value

    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
    

提交回复
热议问题