2013-12-20 26 views
0

如果這是一個愚蠢的問題,請原諒我,但是有沒有代表所有函數的類型類?喜歡,可以說我有這樣的類型代表函數的類型類

data Foo a = Thing a 

instance (Show a) => Show (Foo a) where 
    show (Thing a) = show a 

而我想顯示Thing (\x -> 1)。也許做一些反思的方法漂亮打印一些關於這個元數據?

嘗試它,我得到以下錯誤

> Thing (\x -> 1) 

<interactive>:113:1: 
    No instance for (Show (t0 -> a0)) arising from a use of `print' 
    Possible fix: add an instance declaration for (Show (t0 -> a0)) 
    In a stmt of an interactive GHCi command: print it 

<interactive>:113:14: 
    No instance for (Num a0) arising from the literal `1' 
    The type variable `a0' is ambiguous 
    Possible fix: add a type signature that fixes these type variable(s) 
    Note: there are several potential instances: 
     instance Num Double -- Defined in `GHC.Float' 
     instance Num Float -- Defined in `GHC.Float' 
     instance Integral a => Num (GHC.Real.Ratio a) 
     -- Defined in `GHC.Real' 
     ...plus 11 others 
    In the expression: 1 
    In the first argument of `Thing', namely `(\ x -> 1)' 
    In the expression: Thing (\ x -> 1) 

這是有道理的,因爲沒有的showt0 -> a0實例,但我不知道該如何形容這個類型類的實例?

這不適用於任何生產,我只是亂搞Haskell,並好奇我能做什麼,不能做什麼。

+2

如果你想要一個佔位符實例,所以你可以顯示函數,然後導入'Text.Show.Functions'。 –

+0

很酷,謝謝!我知道我錯過了一些東西。 – devshorts

+1

函數不能是'Show'的實例。看起來好像很簡單,但編譯器在編譯,優化和組裝後很難獲得信息。甚至可以在運行時創建新的函數,因此它使事情變得非常複雜。你可以用模板haskell來管理它,它會產生類似'data Func a = Func a String'類型的值,其中函數定義可以被插入到字符串中,而函數本身可以插入到'a'插槽中。然後你可以爲它創建一個簡單的'Show'實例。但是這會很難寫出來。 – bheklilr

回答

4

既然你的目標只是爲了獲得樂趣,你可能會喜歡Data.Universe.Instances.Show。然而,對於更嚴肅的目標,您可能需要等到Cloud Haskell項目取得了一些進展,該項目部分旨在將函數序列化和反序列化,以便可以跨機器遷移它們。

+0

是否有一些魔法可以在我的電腦死前打印Int64 - > Int64?另外我認爲OP(我也是)希望能夠顯示源代碼,就像在R或Scheme中可以做的那樣。任何方式呢? Cloud Haskell? http://hackage.haskell.org/package/universe-0.4.0.4/docs/src/Data-Universe-Instances-Show.html#Universe – misterbee

+0

@misterbee對,爲了能夠序列化和反序列化代碼,你必須等待爲Cloud Haskell。或者定義你自己的語言並嵌入它。 –

+0

該wiki頁面顯示Cloud Haskell已發佈,並鼓勵使用。此外,看起來像靜態標籤可能會工作,如果程序員願意命名所有可能顯示的「基本」功能和組合器(不是所有功能,但)http://hackage.haskell.org/package/distributed-static- 0.2.1.1/docs/Control-Distributed-Static.html – misterbee