2012-06-01 30 views
4

我想定义一个仿函数实例为以下类别:scalaz'Functor怎样才能给上下限绑定的更高类型?

class RequiresManifest[A: Manifest] { 
    def value: A 
} 

class RequiresAnyRef[A <: AnyRef] { 
    def value: A 
} 

class RequiresBothManifestAndAnyRef[A <: AnyRef: Manifest] { 
    def value: A 
} 

这可能吗?或者可以定义'BoundedFunctor特质?是这样的:

trait BoundedFunctor[F[_], Bound[_]] { 
    def fmap[A: Bound, B: Bound](r: F[A], f: A => B): F[B] 
} 

这里是我的激励例如:如何定义的类TypedConverter函子。

import com.thoughtworks.xstream.converters.Converter 

abstract class TypedConverter[A <: AnyRef: Manifest] extends Converter { 
    final def canConvert(klass: Class[_]) = 
    manifest[A].erasure.isAssignableFrom(klass) 

    final def marshal(value: AnyRef, writer: HierarchicalStreamWriter, 
        context: MarshallingContext) = 
    typedMarshal(value.asInstanceOf[A], writer, context) 

    final def unmarshal(reader: HierarchicalStreamReader, 
         context: UnmarshallingContext) = 
    typedUnmarshal(reader, context) 

    def typedMarshal(value: A, writer: HierarchicalStreamWriter, 
        context: MarshallingContext): Unit 

    def typedUnmarshal(reader: HierarchicalStreamReader, 
        context: UnmarshallingContext): A 
} 

这-kinded更高类型在其类型参数两个约束,第一清单,因为这是在“canConvert”,第二AnyRef的实现中使用的,因为解组需要对象。

其实我试图创建一个InvariantFunctor,但是Functor会做。

+0

我明白了。但有一点对我来说还不清楚:应该怎么使用这个Functor?你能举几个例子说明什么应该工作,哪些不应该工作? – Christian

+0

BoundedFunctor似乎为第一种情况做了诀窍,但我猜想剩下的部分需要一些隐含的jiggerypokery。 – Stacy

回答

2

在数学中,请参阅函子是从一个类到另一个类的映射。在Comp Sci中,人们相信一个函子是一个内部函数,例如对于Scala话语,它是在所有Scala类型上定义的。

这就是scalaz的实现写法。

但它并不一定如此。据我了解,在你的情况下,你有一个子类别(大致由Bound定义);所以函数将从Bound到Scala。

这是一个很好的想法,没有太多的探索。我相信我们必须进一步调查。尽管在编程语言中明确定义类别有点问题。甚至不知道Agda。

+0

感谢您的回复,唉,我仍然无法继续执行。 – Stacy