简体   繁体   中英

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:

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.

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:

 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:

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 ).

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:

// 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):

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):

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

The Scala equivalent is an Enumeration :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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