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

时间:2017-03-03 10:49:35

标签: haskell types monads

考虑以下内容:

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的实例。我该如何明确说明这一点?

1 个答案:

答案 0 :(得分:8)

注释对t的完整调用:

print (t 22 :: Maybe Int)

或注释t本身

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

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

print $ t @Maybe @Int 22

取决于手头的课程,这可以节省您输入很长的注释。