简体   繁体   English

Scala 相当于 Haskell 中的“数据”声明

[英]Scala equivalent of `data` declaration in Haskell

I'm trying to write Scala code in a functional style, and want to create a custom type such as the following Haskell definition:我正在尝试以功能样式编写 Scala 代码,并希望创建一个自定义类型,例如以下 Haskell 定义:

data Day = Mo | Tu | We | Th | Fr | Sa | Su

I know that Scala tends to borrow things from Haskell a fair bit, so was wondering if this kind of declaration is possible in Scala.我知道 Scala 倾向于从 Haskell 借用一些东西,所以想知道这种声明在 Scala 中是否可行。

I don't know Haskell that much, but I just had a quick look, and it seems like data declaration is kind of like an ADT (Algebraic DataType), given this example in haskell website:我不太了解 Haskell,但我只是快速浏览了一下,看起来数据声明有点像ADT (代数数据类型),在 haskell 网站中给出了这个例子:

 data Maybe a = Just a | Nothing

Similar concept to Maybe datatype of Haskell in Scala would be Option , which represents the possibility of existence of a value:与 Scala 中 Haskell 的Maybe数据类型类似的概念是Option ,表示值存在的可能性:

sealed trait Option[+A] { /* some methods */ }
final case class Some[+T](value: T) extends Option[T] { /* some methods */ }
case object None extends Option[Nothing] { /* some methods */ }

In Scala, these kind of DataTypes are almost always represented by a sealed trait, which is the product type, and some subtypes/objects, mostly known as sum types ( Some and None in this case), much like in Haskell ( Just and Nothing ).在 Scala 中,这些类型的 DataTypes 几乎总是由密封特征表示,即产品类型,以及一些子类型/对象,通常称为 sum 类型(在这种情况下为SomeNone ),很像 Haskell( Just and Nothing )。

Now in your case, you don't need those constructors for your data, so you can both represent is as enums, or just use ADTs:现在,在您的情况下,您的数据不需要那些构造函数,因此您既可以将 is 表示为枚举,也可以只使用 ADT:

// using ADT

// define product type
sealed trait Day

// define sum types
case object Mo extends Day
case object Tu extends Day
case object We extends Day
case object Th extends Day
case object Fr extends Day
case object Sa extends Day
case object Su extends Day

Scala 2 enumeration (not recommended in general, but does the work): Scala 2 枚举(一般不推荐,但确实有效):

object Day extends Enumeration {
  type Day = Value
  val Mo, Tu, We, Th, Fr, Sa, Su = Value
}

Or Scala3 enums (your best choice if you're using Scala3):或 Scala3 枚举(如果您使用 Scala3,您的最佳选择):

enum Day:
  case Mo, Tu, We, Th, Fr, Sa, Su

The Scala equivalent is an Enumeration : Scala 等效项是Enumeration

enum Day:
  case Mo, Tu, We, Th, Fr, Sa, Su

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM