2013-02-22 37 views
1

類型別名我有以下類型別名派生式並顯示在Haskell

data Bindable = Const Value 
         | Variable Location 
        | Func Function 
        | Proc 
       deriving (Eq, Show)         

type Function = Argument -> Store -> Value 

但是編譯器給我一個錯誤

No instance for (Show Function) 
arising from the 'deriving' clause of a data type declaration 
Possible fix: 
add an instance declaration for (Show Function) 
or use a standalone 'deriving instance' declaration, 
    so you can specify the instance context yourself 
When deriving the instance for (Show Bindable) 

我可以明確顯示&式的功能?如果不是,那麼解決方案是什麼?我應該將Eq和Show定義爲參數,商店和價值嗎?

回答

4

剛進口Text.Show.Functions。您的type只是一個別名,錯誤消息是說它找不到(->)的顯示實例,但該模塊中有一個實例可用。

Prelude> import Text.Show.Functions 
Prelude Text.Show.Functions> show (+1) 
"<function>" 
+0

托馬斯感謝快速幫助!它解決了Show的問題。我應該爲Eq導入什麼? – 2013-02-22 02:14:41

+0

你必須編寫自己的實例(默認爲True或False取決於你想要的)。 '實例Eq函數,其中_ == _ = True' – 2013-02-22 02:21:31

5

類型類實例可以僅對於「真正的」類型來定義,由一個或data聲明newtype所定義。 A type聲明是「假」類型 - 只是較長類型的縮寫。

但這只是問題#1在這種情況下。問題二是,即使你做到這一點...

newtype Function = Function (Argument -> Store -> Value) 

...有可能仍然沒有對Function真正有用Show實例。如何將函數轉換爲字符串?有兩種策略。首先,「乾脆放棄」的策略:

instance Show Function where 
    show _ = "<some Function, no clue what it does>" 

二,「典型的例子」的策略,在這裏應用Function一些規範ArgumentStore,並與Value結果一起顯示這些:

instance Show Function where 
    show (Function fn) = "Function: " 
         ++ show defaultArgument 
         ++ " -> " 
         ++ show defaultStore 
         ++ " -> " 
         ++ show (fn defaultArgument defaultStore) 

這裏的想法是,以顯示它的Function作爲一個特定的參數/值映射,可以幫助您識別更準確比只使用相同的常量字符串爲他們所有。這是否有幫助取決於你的功能。

但是現在我們有了問題#3:這些都不服從的意圖/的ShowRead類的合同,這是read (show x)相當於x。 (然而,人們經常忽略這個意圖,只是因爲他們想打印和Show是最快的票據。正如Thomas DuBuisson指出的那樣,有一個標準模塊Text.Show.Functions實現了「放棄」策略。)

對於Eq類,得到的答覆是,它一般只是無法比較兩種功能是否相等。 (如果我沒有記錯,這是等同於解決停機問題,但不可以引用我這句話。)如果您的解決方案需要你,你需要一個新的解決方案,比較功能平等......

+1

說明兩個程序在存在上是否相同,與解決暫停問題一樣困難。你必須知道一個函數是否停止以知道它是平等的!或者,也可以使用'solveHalting f =(\ y - > seq(f x)y)== id'。我們知道'solveHalting'不能由Turing的證明存在,所以沒有得到這樣的'Eq'實例的功能。 – 2013-02-22 03:02:50

+0

是的,我明白你對展會的看法,它對我來說確實很有意義。對於Eq,問題是我必須讓Bindable來派生Eq,因爲我需要它來獲取其他函數的Value和Location。儘管對於函數和過程我不需要它,但是我也必須讓它們成爲Bindables。你看到我的問題了嗎? – 2013-02-22 03:14:04

+0

也許你可以重新定義'Function'來包含一個函數名並比較它?取決於你的用例。 – firefrorefiddle 2013-02-22 10:37:00