2012-06-01 25 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