2012-06-03 45 views
7

我想爲(二進制)函數實現show方法,並使其能夠執行函數(a -> a)函數「show」的實現

有點像僞Haskell代碼:

instance Show (a->b) where 
    show fun = "<<Endofunction>>" if a==b 
    show fun = "<<Function>>" if a\=b 

我如何能夠區分兩種情況?

+0

這根本不是一個很好的'Show'實例。你應該寫一些像'isEndo ::(a-> b) - > Bool'這樣的東西,然後用一個簡單的警衛在你想要的地方創建合適的文本。 – leftaroundabout

+2

「const 3」是函數還是函數? –

+1

@DanielWagner:是的。 – Ashe

回答

15

您需要啓用一些擴展:

{-# LANGUAGE OverlappingInstances, FlexibleInstances #-} 
module FunShow where 

instance Show ((->) a a) where 
    show _ = "<<Endofunction>>" 

instance Show ((->) a b) where 
    show _ = "<<Function>>" 

您需要OverlappingInstances,因爲實例a -> b也匹配endofunctions,所以有重疊,你需要FlexibleInstances因爲語言標準規定,在實例聲明的類型變量不同。

*FunShow> show not 
"<<Endofunction>>" 
*FunShow> show fst 
"<<Function>>" 
*FunShow> show id 
"<<Endofunction>>"