我試圖讓下面的代碼工作(當然,編譯第一!):如何從類型函數中「推導出」其中的一個實例時使用多個「數據」實例?
module Orexio.Radix where
import Data.Data
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Typeable
import Text.JSON.Generic
class Resource a where
type Representation a :: *
identifier :: Resource a => Identifier a
class Endpoint a where
call :: Resource a => a -> Representation a
data Identifier a = Identifier [String] deriving (Show)
data Binding a = Binding (JSValue -> Either String JSValue)
bind :: (Data a, Resource a, Endpoint a, Data (Representation a)) => Binding a
bind = Binding (\x -> binding $ query x)
where binding query = fmap (\x -> toJSON $ call x) (resultToEither query)
query jsvalue = fromJSON jsvalue
{-- DEMO --}
data HelloWorld = HelloWorld {
name :: String
} deriving (Show, Typeable, Data)
instance Resource HelloWorld where
type Representation HelloWorld = String
identifier = Identifier ["helloworld"]
instance Endpoint HelloWorld where
call r = "Hello " ++ name r
所以我不得不啓用FlexibleContexts
能夠做到Data (Representation a)
,但它仍然不工作...
我有這樣的錯誤:
src/Orexio/Radix.hs:21:33:
Could not deduce (Data a0) arising from a use of `query'
from the context (Data a,
Resource a,
Endpoint a,
Data (Representation a))
bound by the type signature for
bind :: (Data a, Resource a, Endpoint a,
Data (Representation a)) =>
Binding a
at src/Orexio/Radix.hs:20:9-78
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 Data HelloWorld -- Defined at src/Orexio/Radix.hs:29:29
instance Data() -- Defined in `Data.Data'
instance (Data a, Data b) => Data (a, b) -- Defined in `Data.Data'
...plus 42 others
In the second argument of `($)', namely `query x'
In the expression: binding $ query x
In the first argument of `Binding', namely
`(\ x -> binding $ query x)'
老實說我還挺丟在這裏,我必須失去了一些東西,但什麼?
這裏是我已經激活了其他擴展:DeriveDataTypeable
,ExistentialQuantification
,NoMonomorphismRestriction
,TypeFamilies
提前感謝!
按照建議GHC給你:「可能的修復:添加修復這些類型變量的類型簽名」 –
@SjoerdVisscher我試圖把它們放在不同的位置(在查詢RHS和綁定RHS),但沒有成功。你會把他們放在哪裏? –