Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading