簡體   English   中英

了解高級類型函數

[英]Understanding Higher Kinded Type Function

給定的ParentResult代數數據類型:

sealed trait Parent
case object Kid extends Parent

sealed trait Result[A <: Parent]
case class ResultImpl[A <: Parent](x: A) extends Result[A]

然后我寫道:

def general[A <: Parent, F[_]](x: A, f: A => F[A]): F[A] = 
  f(x)

但是,我不確定如何調用general來獲取ResultImpl[Kid.type]類型的輸出。

我嘗試過:

scala> general(Kid, ResultImpl.apply)
<console>:19: error: inferred kinds of the type arguments (Kid.type,ResultImpl) do not conform to the expected kinds of the type parameters (type A,type F).
ResultImpl's type parameters do not match type F's expected parameters:
type A's bounds <: Parent are stricter than type _'s declared bounds >: Nothing <: Any
       general(Kid, ResultImpl.apply)
       ^
<console>:19: error: type mismatch;
 found   : Kid.type
 required: A
       general(Kid, ResultImpl.apply)
               ^
<console>:19: error: type mismatch;
 found   : Nothing => ResultImpl[Nothing]
 required: A => F[A]
       general(Kid, ResultImpl.apply)
                               ^

我該如何使用general功能?

您還需要指定_<: Parent ,因為A是。 另外,您可能希望將參數分成兩組,以便編譯器正確推斷A

def general[A <: Parent, F[_ <: Parent]](x: A)(f: A => F[A]): F[A] =
              f(x)

然后下一個按預期工作:

general(Kid)(ResultImpl(_))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM