我想用Debug.Trace.trace
打印一些我知道的是Show
。就像我在Python做等Haskell:任何debugShow函數?
一種解決方案是增加「Show a =>
」的地方,我希望把跟蹤功能的簽名,以及任何函數調用它,等
但如果我可以使用debugShow
函數調用show
(如果該值爲1),則返回值會更好,否則返回"--no show--"
或其他值。
這是我失敗的嘗試定義DebugShow
(GHC拒絕"Duplicate instance declarations"
):
{-# LANGUAGE FlexibleInstances, UndecidableInstances, OverlappingInstances #-}
class DebugShow a where
debugShow :: a -> String
instance Show a => DebugShow a where
debugShow = show
instance DebugShow a where
debugShow = const "--no show--"
某種「不安全投」也能解決我的問題。
有什麼建議嗎?
注 - 這僅用於調試目的。我沒有在任何完成的代碼中使用它。
@ephemient:謝謝。在這種情況下,我似乎可以使用'unsafeCoerce'來「投射」到一個特定的類型,但我想將它「投射」到相同的未知類型並在其上下文中添加「Show」。我試圖定義「`debugShow = show。unsafeCoerce`」,但是因爲「`Ambiguous type variable`」而失敗了。「 – yairchu 2009-07-20 16:31:13