Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what makes a class/trait in scala an ADT

what are the requirements for a Scala trait/class to be classified as a ADT

  • are all sealed traits/classes in scala an ADT? or does it need more properties to qualify to be an ADT say for example support for method fold?
  • should all implementation of sealed traits/classes be a case class? The documentation here says the below

    automatic mapping between algebraic data types (ADTs) (encoded in Scala as case classes and sealed traits) and these generic representations.

like image 526
rogue-one Avatar asked Jun 15 '18 12:06

rogue-one


1 Answers

An algebraic data type is a kind of composite type, i.e., a type formed by combining other types.

Definition taken from Wikipedia

What is product type?

class Person(name: String, age: Int)

Person type is formed by combining name and age types.

You need both name and age to construct the Person type. Meaning Person is the product (algebraic product, not mathematical product) of name and age types.

What is sum type?

trait Closable
class File(path: String) extends Closable
class Socket(port: Int) extends Closable

Closable can be created by either File or Socket. One of them is enough for making an instance of Closable. File and Socket are called sum types.

Why sealed?

sealed is not compulsory, but its good practice.

What happens when you use sealed?

sealed trait Closable
class File(path: String) extends Closable
class Socket(port: Int) extends Closable

You cannot declare another sub type of Closable in another file. All the sub types have to present in single file. This stops pattern matching from giving Match Error. All subtypes with be in one file and only library author will be able to add more subtypes (in case of library).

Why case?

case is for scala compiler to generate

  1. Class companion object with apply, applySeq, unapply and unapplySeq methods
  2. Also equals, copy, toString etc are also generate automatically
  3. Its helps in de-structuring the case class when patten matching.

What about fold?

fold is entirely another concept it has nothing to do with ADTs

Finally, ADTs look like this

sealed trait Closable
case class File(path: String, name: String) extends Closable
case class Socket(port: Int) extends Closable

also there can be abstract class as well

sealed abstract class Closable
case class File(path: String, name: String) extends Closable
case class Socket(port: Int) extends Closable

Haskell ADTs

data Closable = File { path :: String, name :: String } | Socket { port :: Int }

But, In Scala sum types are simulated using inheritance

like image 123
pamu Avatar answered Oct 15 '22 07:10

pamu