【问题标题】:How to read complex scala type definition as in ```type Pipe[F[_], -I, +O] = Stream[F, I] => Stream[F, O] ```如何读取复杂的 scala 类型定义,如 ```type Pipe[F[_], -I, +O] = Stream[F, I] => Stream[F, O] ```
【发布时间】:2021-08-10 07:04:00
【问题描述】:

type Pipe[F[_], -I, +O] = Stream[F, I] => Stream[F, O]

我了解F[_]-I+O。缺少的部分是右侧的F。为什么不Stream[F[_]]? 我猜左边和右边的F有不同的含义。有没有关于写类型定义规则的官方文档?

我检查 Stream 的类型,

scala> :kind fs2.Stream
fs2.Stream's kind is X[+F[A1],+A2]

另一种情况:

scala> trait Functor [F[_]] {
     |    def map[A,B] (fn: A=>B)(fa: F[A]): F[B]
     | }
trait Functor

scala> :kind Functor
Functor's kind is X[F[A]]

为什么F[A] 没有被 F 替换?当然,我对不同的概念感到困惑,但是我应该在哪里学习它们。

【问题讨论】:

    标签: scala generics scala-cats


    【解决方案1】:

    我猜左右的F有不同的意思

    更准确地说,左右两边的下划线_ 有不同的含义。前者代表匿名类型参数,而后者代表适当的通配符类型。 Scala 3 的未来版本最终应该将含义变为 same

    它还删除了用作类型参数的疣,F[_] 表示 F 是类型构造函数,而用作类型,F[_] 表示它是 通配符(即存在)类型。在未来,F[_] 将意味着 一样的东西,不管用在哪里

    为了说明这一点考虑

    scala> trait Foo[F[_]]
    // defined trait Foo
    
    scala> type Bar[F[_]] = Foo[F[_]]
    1 |type Bar[F[_]] = Foo[F[_]]
      |                     ^^^^
      |         Type argument F[?] does not have the same kind as its bound [_$1]
    
    scala> type Bar[F[_]] = Foo[F[?]]
    1 |type Bar[F[_]] = Foo[F[?]]
      |                     ^^^^
      |         Type argument F[?] does not have the same kind as its bound [_$1]
    
    scala> type Bar[F[_]] = Foo[([x] =>> F[x])[?]]
    1 |type Bar[F[_]] = Foo[([x] =>> F[x])[?]]
      |                     ^^^^^^^^^^^^^^^^^
      |       Type argument F[Any] does not have the same kind as its bound [_$1]
    

    注意右边的下划线是如何等价的

    ([x] =>> F[x])[?]
    

    其中类型 lambda [x] =>> F[x] 应用于正确类型 ?,从而产生正确类型 ([x] =>> F[x])[?]。但是Foo 是高阶类型构造函数,它期望另一个类型构造函数作为参数,而不是正确的类型。因此以下作品

    scala> type Bar[F[_]] = Foo[F]
    // defined alias type Bar[F] = Foo[F]
    
    scala> type Bar[F[_]] = Foo[[x] =>> F[x]]
    // defined alias type Bar[F] = Foo[F]
    

    注意类型 lambda [x] =>> F[x] 必须如何传递给 Foo“未应用”。

    【讨论】:

    • type Pipe[F[_], -I, +O] = Stream[F, I] => Stream[F, O] 可以“读取”为类型 Pipe[[X] = >> F[X], -I, +O] = 流[F, I] => 流[F, O]。这是正确的吗?这更平易近人
    猜你喜欢
    • 2011-07-11
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2012-12-08
    • 2012-04-19
    • 1970-01-01
    • 2012-04-13
    • 2022-01-20
    相关资源
    最近更新 更多