[英]How to tell GHC what fromIntegral should do
data N_ary = N_ary Int String Int deriving Eq
將數字存儲到各種基礎。 例如,到基數N_ary 1 "1111" 2
和16的15分別是N_ary 1 "1111" 2
, N_ary 1 "15" 10
和N_ary 1 "F" 16
。 (第一個字段是-1、0或1作為符號。)
我定義了一個用於將事物轉換為N_ary
對象的運算符infixl 5 ~>
和一個用於可轉換類型的類。
class N_aryAble a where
(~>) :: a -> Int -> N_ary
我對instance N_aryAble Integer
或instance N_aryAble N_ary
(將一個基數更改為另一個基數)沒有任何問題,但是我遇到了一個問題
instance N_aryAble Int where
int ~> base = fromIntegral int ~> base
Ambiguous type variable ‘a0’ arising from a use of ‘fromIntegral’
prevents the constraint ‘(Num a0)’ from being solved.
...
Ambiguous type variable ‘a0’ arising from a use of ‘~>’
prevents the constraint ‘(N_aryAble a0)’ from being solved.
...
如果沒有特殊設置,則不允許實例聲明中的類型簽名。
instance N_aryAble Int where
(~>) :: Int -> Int -> N_ary
int ~> base = fromIntegral int ~> base
Illegal type signature in instance declaration:
(~>) :: Int -> Int -> N_ary
(Use InstanceSigs to allow this)
以下作品。
instance N_aryAble Int where
int ~> base = fromIntegral int + (0::Integer) ~> base
> (5::Int) ~> 2 ==> N_ary 1 "101" 2
但這似乎是丑陋且臨時的 。 有沒有更好的辦法?
謝謝。
您可以為fromIntegral
調用提供類型注釋,以使其不模糊。
instance N_aryAble Int where
int ~> base = (fromIntegral int :: Integer) ~> base
問題不在於編譯器無法推斷出from轉換為from的類型。 可以使用該特定實例方法的簽名來解決,順便說一句,您可以這樣寫
instance N_aryAble Int where
(~>) = (~~>)
where (~~>) :: Int -> Int -> N_ary
int ~~> base = fromIntegral int ~> base
但是該信息已經從類方法簽名中清除了,因此對您沒有幫助。
不,問題在於您沒有指定要轉換為哪種類型,並且由於~>
的參數再次是多態的,因此編譯器沒有其他可推斷出的類型。 這也可能將Int
轉換為Int
,從而導致無限遞歸循環,因為最終您將嘗試定義相同的~>
實例!
您可以使用chi所示的fromIntegral
結果的簽名來闡明這一點,也可以簡單地將單態轉換函數與Integer
結果一起使用to-
version:
instance N_aryAble Int where
int ~> base = toInteger int ~> base
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.