這是一個挑戰問題,而不是一個有用的問題(我花了幾個小時)。鑑於一些功能,如何在Haskell中編寫一系列printf函數(調試打印等)
put_debug, put_err :: String -> IO()
put_foo :: String -> StateT [String] m()
我想寫一個廣義的printf函數,調用它GPRINT,這樣我可以寫
pdebug = gprint put_debug
perr = gprint put_err
pfoo = gprint put_foo
然後用pdebug
,perr
和pfoo
像printf
,例如,
pdebug "Hi"
pdebug "my value: %d" 1
pdebug "two values: %d, %d" 1 2
我無法想出一個足夠一般的班級。我嘗試過的事情一樣(對於熟悉Printf
,或Oleg的可變參數函數的方法)
class PrintfTyp r where
type AppendArg r a :: *
spr :: (String -> a) -> String -> [UPrintf] -> AppendArg r a
或
class PrintfTyp r where
type KRetTyp r :: *
spr :: (String -> KRetTyp r) -> String -> [UPrintf] -> r
兩者都太難寫基地的實例爲:有沒有好的選擇。r
對於第一種方法(並且,其類型不反映在非內射索引類型家族AppendArg
中),並且在第二種方法中,最終寫入instance PrintfTyp a
,其看起來不正確(匹配太多類型)。
同樣,這只是一個挑戰問題:只有在它很有趣的時候纔會這樣做。儘管如此,我一定會好奇地知道答案。謝謝!!
呀,我想避免終結者。我更感興趣的是隻支持一個參數,即不支持'pdebug「無參數」''的情況。不過謝謝。 – gatoatigrado 2012-03-05 18:46:56