haskellgenericstype-systems

What is the Haskell equivalence of Rust's associated types?


What is the Haskell equivalence of Rust's associated types?


Solution

  • Haskell has associated type families. The Contains example on the linked page can be written in Haskell like this:

    {-# LANGUAGE TypeFamilies #-}
    
    class Contains a where
      type A a
      type B a
      contains :: a -> A a -> B a -> Bool
    
    data Container = MkContainer Int Int
    
    instance Contains Container where
      type A Container = Int
      type B Container = Int
      contains (MkContainer x y) a b = x == a && y == b