首页 > 解决方案 > 使用 typeclass 方法的默认实现来省略参数

问题描述

标签: haskelltypeclass

解决方案


The problem is in the default definition of specific. Let's zoom out for a second and see what types your methods are actually given, based on your type signatures.

specific :: forall a b. MyType a b => b -> a -> a
dontCare :: forall a b. MyType a b => a -> a

In the default definition of specific, you use dontCare at type a -> a. So GHC infers that the first type argument to dontCare is a. But nothing constrains its second type argument, so GHC has no way to select the correct instance dictionary to use for it. This is why you ended up needing AllowAmbiguousTypes to get GHC to accept your type signature for dontCare. The reason these "ambiguous" types are useful in modern GHC is that we have TypeApplications to allow us to fix them. This definition works just fine:

class MyType a b where
    specific :: b -> a -> a
    specific = const (dontCare @_ @b)
    dontCare :: a -> a
    dontCare = specific (undefined :: b)
    {-# MINIMAL specific | dontCare #-}

The type application specifies that the second argument is b. You could fill in a for the first argument, but GHC can actually figure that one out just fine.


推荐阅读