我想定義一個仿函數實例爲以下類別: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會做。
我明白了。但有一點對我來說還不清楚:應該怎麼使用這個Functor?你能舉幾個例子說明什麼應該工作,哪些不應該工作? – Christian
BoundedFunctor似乎爲第一種情況做了訣竅,但我猜想剩下的部分需要一些隱含的jiggerypokery。 – Stacy