【问题标题】:Explicitly specifying the return type of a class method?显式指定类方法的返回类型?
【发布时间】:2017-03-03 10:49:34
【问题描述】:

考虑以下:

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

【问题讨论】:

    标签: haskell types monads


    【解决方案1】:

    注释对t的完整调用:

    print (t 22 :: Maybe Int)
    

    或注释t本身

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

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

    print $ t @Maybe @Int 22
    

    根据手头的课程,这可能会节省您输入很长的注释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 2011-12-27
      • 1970-01-01
      • 2019-12-14
      相关资源
      最近更新 更多