2017-03-03 49 views
1

考慮如下:顯式指定類方法的返回類型?

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的方式。我怎樣才能明確說明這一點?

回答

8

標註完整的呼叫t

print (t 22 :: Maybe Int) 

或註釋t本身

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

隨着更先進的替代方案,以在適當的擴展,可以明確地傳遞類型級別參數

print $ t @Maybe @Int 22 

取決於在ha級nd,這可以幫助您輸入非常長的註釋。

相關問題