明确指定类方法的返回类型?

Bab*_*ham 1 monads haskell types

考虑以下内容:

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! 
Run Code Online (Sandbox Code Playgroud)

抛出以下错误:

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

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

chi*_*chi 8

注释完整调用t:

print (t 22 :: Maybe Int)
Run Code Online (Sandbox Code Playgroud)

或注释t自己

print $ (t :: Int -> Maybe Int) 22
Run Code Online (Sandbox Code Playgroud)

作为一种更高级的替代方案,通过适当的扩展,可以明确地传递类型级别参数

print $ t @Maybe @Int 22
Run Code Online (Sandbox Code Playgroud)

根据手头的类,这可以节省您输入很长的注释.