我想如下定義一個特定函子:Haskell的類型類與參數類型
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
data ValOrError a b = Val a | Error b
class MF c a b where
mcons :: a -> c -> c
merr :: b -> c
mhead :: c -> ValOrError a b
mtail :: c -> ValOrError c b
32,我想在c
類型的類型類MF
具有類型參數a
和b
。我想在這樣的數據結構定義過濾器的功能如下:
mfilter f e =
let h = mhead e in
let t = mtail e in
case h of
Error b -> e
Val a -> case (f a) of
True -> case t of
Error d -> mcons a (merr d)
Val b -> mcons a (mfilter f b)
False -> case t of
Error d -> merr d
Val b -> mfilter f b
但我得到了以下錯誤:
haskell.hs:24:1:
Could not deduce (MF c a2 b3) arising from the ambiguity check for ‘mfilter’ from the context (MF c a5 b6, MF c a4 b5, MF c a4 b4, MF c a4 b, MF c a3 b6, MF c a b6) bound by the inferred type for ‘mfilter’: (MF c a5 b6, MF c a4 b5, MF c a4 b4, MF c a4 b, MF c a3 b6, MF c a b6) => (a4 -> Bool) -> c -> c at haskell.hs:(24,1)-(35,28) The type variables ‘a2’, ‘b3’ are ambiguous When checking that ‘mfilter’ has the inferred type ‘forall b c a b1 a1 a2 b2 a3 b3. (MF c a3 b3, MF c a2 b2, MF c a2 b1, MF c a2 b, MF c a1 b3, MF c a b3) => (a2 -> Bool) -> c -> c’ Probable cause: the inferred type is ambiguous
我不知道是否有在Haskell一個更好的方式來聲明類型c
始終具有a
和b
作爲類型參數。使用Java的語法:
public interface MF<A,B> {
MF<A,B> mcons(A head, MF<A,B> tail);
MF<A,B> merr(B error);
ValOrError<A,B> head(MF<A,B> e);
ValOrError<MF<A,B>,B> tail(MF<A,B> e);
}
此外,在另一方面,過濾功能應該有一個類型:
mfilter :: (a -> Bool) -> MF c a b -> MF c a b
我有一個問題,關於最後的解決方案,我最喜歡的。如果我有以下數據 'data MemoryMonad a b = Lift b |守衛b | Elem a(MemoryMonad a b)' 我該如何讓它成爲這個類型類的一個實例? – jackb
@jackb'instance MF(MemoryMonad a b)where type ValType(MemoryMonad a b)= a;鍵入ErrType(MemoryMonad a b)= b' – user2407038