这可以通过在类定义中定义通用方法并在实例中覆盖它来使用类型类来完成。将始终使用被覆盖的函数。
class ContainsInt c where
toList :: c -> [Int]
-- generic function
elem :: Int -> c -> Bool
elem n x = Prelude.elem n (toList x)
instance ContainsInt () where
toList _ = []
-- Override the generic function for type ()
elem _ _ = False
GHC 支持的另一种方法是使用重写规则。重写规则告诉 GHC 尽可能用另一个表达式替换一个表达式。如果替换是错误类型的,则不会执行,因此您可以使用它来替换专用版本的函数。重写规则由{-# RULES #-}
pragma 给出。
class ContainsInt c where
toList :: c -> [Int]
elem :: ContainsInt c => Int -> c -> Bool
elem n x = Prelude.elem n (toList x)
-- Replace 'elem' by 'elemUnit' if it has the same type
{-# RULES "elem()" forall. elem = elemUnit #-}
elemUnit :: Int -> () -> Bool
elemUnit _ _ = False
重写规则由编译器自行决定执行,因此在任何给定情况下可能会或可能不会调用专用函数。例如,重写可能取决于编译器是否决定内联函数:
foo :: ContainsInt c -> Int -> [c] -> [Bool]
-- Must use the generic function
foo n cs = map (elem n) cs
useFoo :: Int -> [()] -> [Bool]
-- If 'foo' is inlined and 'elem' is not inlined, then this function will contain a rewritable call to 'elem'.
-- Otherwise rewriting cannot happen.
useFoo n cs = foo n cs