我不明白为什么 Haskell 无法在以下代码中找出第 8 行的类型。expressMaybe 函数的类型签名不是确定结果类型与两个输入参数的类型相同吗?
{-# LANGUAGE MultiParamTypeClasses #-}
class Gene g n where
express :: g -> g -> g
-- there will be other functions that use the "n" type parameter
expressMaybe :: Gene g n => Maybe g -> Maybe g -> Maybe g
expressMaybe (Just a) (Just b) = Just (express a b) -- line 8
expressMaybe (Just a) Nothing = Just a
expressMaybe Nothing (Just b) = Just b
expressMaybe Nothing Nothing = Nothing
我得到的错误是:
Amy20.hs:8:40:
Ambiguous type variable `n0' in the constraint:
(Gene g n0) arising from a use of `express'
Probable fix: add a type signature that fixes these type variable(s)
In the first argument of `Just', namely `(express a b)'
In the expression: Just (express a b)
In an equation for `expressMaybe':
expressMaybe (Just a) (Just b) = Just (express a b)
Failed, modules loaded: none.
我尝试使用 RankNTypes 和 ScopedTypeVariables,但我不知道如何使错误消失。
预先感谢您的帮助!
编辑:既然我理解了这个问题,我使用了fundeps,因为我对它们很熟悉,而且对于我的应用程序来说,拥有多个用于编码基因的“字母表”没有多大意义。不过,我以前从未使用过类型族,所以我也会研究一下。
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
class Gene g n | g -> n where
express :: g -> g -> g
-- there will be other functions that use the "n" type parameter
expressMaybe :: Gene g n => Maybe g -> Maybe g -> Maybe g
expressMaybe (Just a) (Just b) = Just (express a b) -- line 8
expressMaybe (Just a) Nothing = Just a
expressMaybe Nothing (Just b) = Just b
expressMaybe Nothing Nothing = Nothing