2017-11-11 101 views
2

我有一個類型,我已經做了Show類的實例,但我沒有得到期望的結果。如果我嘗試使用deriving字,然後它工作,使之秀類的實例,但如果嘗試像:哈希克爾派生和實例之間的區別

instance Show (SomeValue v) where 
    show (Null) = "You have no value" 
    show (Justs v) = show (Justs v) 

findKey key = foldr (\(k,v) acc -> if key == k then Justs v else acc) Null 

它去在未結束循環(種)。我認爲,通過使用deriving單詞得到的默認實現工作,上面的代碼有什麼問題?它編譯但它不打印任何東西。

是否有可能我打印這樣的值:(沒有「Justs」)?

instance Show (SomeValue v) where 
    show (Null) = "You have no value" 
    show (Justs v) = show (v) 
+0

相關:https://stackoverflow.com/questions/28665917/accessing-the-default-show-in-haskell –

+0

@WillemVanOnsem它不一樣。對於我的數據構造函數,我只有兩個值,對於這兩個值我已經定義了show,但它不打印任何東西,我甚至嘗試使用type-annotations進行讀取,但它不起作用:) –

+0

當然,它確實不打印任何東西,它被卡在無限循環中。 –

回答

3

代碼

show (Justs v) = show (Justs v) 

進入一個無限循環出於同樣的原因

f x = f x 

一樣。

你可以把它寫不Justs爲你問,你只需要一個約束的情況下


instance (Show v) => Show (SomeValue v) where 
    show Null = "You have no value" 
    show (Justs v) = show v 

,因爲如果你要儘量表現出vv應該showable,不是嗎?