3 ms·
> Late function binding allows you to operate over heterogeneous inputs where the only thing you want to enforce is that they obey a protocol… You can do that
by nybble41 6y ago
> Late function binding allows you to operate over heterogeneous inputs where the only thing you want to enforce is that they obey a protocol…
You can do that in typeclass-based languages as well, e.g. in Haskell:
{-# LANGUAGE ConstraintKinds, ExistentialQuantification #-}
data Constrained c = forall a. c a => C a
showAll :: [Constrained Show] -> [String]
showAll xs = map (\(C x) -> show x) xs
main = foldMap putStrLn $ showAll [C (1 :: Integer), C ("abc" :: String), C (3.14 :: Double)]
The `showAll` function takes a list of objects that implement the `Show` typeclass. The objects themselves can be of different types. The syntax is slightly less ergonomic, but the runtime effect is much as you would expect from an OOP language—a pointer to the typeclass dictionary ("vtbl") is paired with each object, and the address of the appropriate `show` method is looked up at runtime for each element of the list.