Scala 中的递归类型定义 [英] Recursive type definition in Scala

查看:46
本文介绍了Scala 中的递归类型定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 Haskell 中有这段代码,我想尝试在 Scala 中想出类似的东西:

Suppose I have this code in Haskell and I want to try to come up with something like it in Scala:

data CatList q a = E | C a (q (CatList q a))

instance Queue q => CatenableList (CatList q) where
   -- methods

请注意,CatList 要么是空的,要么是一个元素加上一个 CatList 的队列(由类型类 q 定义).在 Scala 中,我正在尝试做类似

Note that CatList is either empty, or is an element plus a queue (as defined by a typeclass q) of CatLists. In Scala, I'm trying to do something like

sealed trait CatList[+Q, +E]

object Empty extends CatList[Nothing, Nothing]

case class C[Q[_], E](x: E, q: Q[CatList[Q, E]]) extends CatList[Q[???], E]

但问题是,Q[_] 需要参数,所以我需要在 extends 子句中提供一些东西,这导致 CatList[Q[CatList[Q[???], E], E] 令人困惑.

but the problem is, Q[_] takes parameters, so I need to provide something in the extends clause, which leads to CatList[Q[CatList[Q[???], E], E] which is confusing.

我可以尝试使用 Haskell 方法,说 Q[_] 只是一种类型,然后使用

I can try a Haskell approach, saying that Q[_] is nothing but a type, and go with

sealed trait CatList[+Q[_], +E]

object Empty extends CatList[Nothing, Nothing]

case class C[Q[_], E](x: E, q: Q[_]) extends CatList[Q[_], E]

但是失败了

Error:(16, 56) Q[_] takes no type parameters, expected: one
  case class C[Q[_], E](x: E, q: Q[_]) extends CatList[Q[_], E]
                                                       ^

所以问题是,有没有办法解决这个问题?

So the question is, is there a way to get around that?

推荐答案

您需要

sealed trait CatList[+Q[_], +E]

object Empty extends CatList[Nothing, Nothing]

case class C[+Q[_], +E](x: E, q: Q[CatList[Q, E]]) extends CatList[Q, E]

[_] 在类型参数声明中具有不同的含义,例如 trait CatList[+Q[_], +E] ("Q是一个类型构造函数"),并且像extends CatList[Q[_], E](Q with some unknown parameter")一样使用.

[_] has different meanings in type parameter declaration like trait CatList[+Q[_], +E] ("Q is a type constructor") and in use like extends CatList[Q[_], E] ("Q with some unknown parameter").

这篇关于Scala 中的递归类型定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆