Odo*_*ois 5 haskell type-systems typeclass
我是Haskell的新手,只是玩了一会儿.
我写了一个轻量级的OOP模拟:
--OOP.hs
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, UndecidableInstances, ScopedTypeVariables, FunctionalDependencies #-}
module OOP where
class Provides obj iface where
provide::obj->iface
(#>)::obj->(iface->a)->a
o #> meth = meth $ provide o
class Instance cls obj | obj -> cls where
classOf::obj->cls
class Implements cls iface where
implement::(Instance cls obj)=>cls->obj->iface
instance (Instance cls obj, Implements cls iface)=>Provides obj iface where
provide x = implement (classOf x::cls) x
Run Code Online (Sandbox Code Playgroud)
使用它像:
--main.hs
{-# LANGUAGE MultiParamTypeClasses #-}
import OOP
data I1 = I1
getI1::I1->String
getI1 i1 = "Interface 1"
data I2 = I2
getI2::I2->String
getI2 i2 = "Interface 2"
data C = C
instance Implements C I1 where
implement C o = I1
instance Implements C I2 where
implement C o = I2
data O = O
instance Instance C O where
classOf o = C
main = do
putStrLn (O #> getI1)
putStrLn (O #> getI2)
Run Code Online (Sandbox Code Playgroud)
我读到该UndecidableInstances功能非常不方便,可能导致编译器中的堆栈溢出.所以我有两个问题.
1 to N实例和类数据类型之间以及接口和类之间的关系?在这种情况下,您使用不可判定的实例是可以的。
instance (Instance cls obj, Implements cls iface)=>Provides obj iface where
Run Code Online (Sandbox Code Playgroud)
是不可判定的,因为您可能有一个 forInstance或 的实例Implements,而该实例又依赖于Provides导致循环。
但是,在这种情况下,您根本不需要该类Provides,因为您只根据其他两个类的方法给出了它的实现!
相反,您可以将其拉出provides为#>具有适当的Instance和Implements约束的顶级函数,并且您不会丢失任何内容,并且避免了对不可判定实例的需要。
不过,您确实需要/想要 MPTC,这很好......