显式指定 class 方法的 return 类型?

Explicitly specifying the return type of a class method?

考虑以下:

class Test m a where
   t :: Int -> m a

instance Test [] Int where
   t i = [i]

instance Test Maybe Int where
   t i | i == 0   = Nothing
       | otherwise = Just i

main = do 
  print $ t (22 :: Int) --Error! 

这将引发以下错误:

Ambiguous type variables ‘m0’, ‘a0’ arising from a use of ‘print’
  prevents the constraint ‘(Show (m0 a0))’ from being solved.

这是因为编译器无法识别要使用的 m a 的实例。我该如何明确说明这一点?

注释对 t 的完整调用:

print (t 22 :: Maybe Int)

或注释t本身

print $ (t :: Int -> Maybe Int) 22

作为一种更高级的替代方法,通过适当的扩展,可以显式传递类型级参数

print $ t @Maybe @Int 22

根据手头的 class,这可能会避免您输入很长的注释。