7
我想爲(二進制)函數實現show
方法,並使其能夠執行函數(a -> a)
。函數「show」的實現
有點像僞Haskell代碼:
instance Show (a->b) where
show fun = "<<Endofunction>>" if a==b
show fun = "<<Function>>" if a\=b
我如何能夠區分兩種情況?
我想爲(二進制)函數實現show
方法,並使其能夠執行函數(a -> a)
。函數「show」的實現
有點像僞Haskell代碼:
instance Show (a->b) where
show fun = "<<Endofunction>>" if a==b
show fun = "<<Function>>" if a\=b
我如何能夠區分兩種情況?
您需要啓用一些擴展:
{-# 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>>"
這根本不是一個很好的'Show'實例。你應該寫一些像'isEndo ::(a-> b) - > Bool'這樣的東西,然後用一個簡單的警衛在你想要的地方創建合適的文本。 – leftaroundabout
「const 3」是函數還是函數? –
@DanielWagner:是的。 – Ashe