简体   繁体   中英

How to convert the Scala case class definition to Haskell?

I'm learning Haskell along with Scala. I tried to do define the following Scala type in Haskell, but failed:

sealed trait Expr
case class Value(n: Int) extends Expr
case class Add(e1: Expr, e2: Expr) extends Expr
case class Subtract(e1: Expr, e2: Expr) extends Expr

Could someone give me an example?

In scala, union types are emulated with a sealed class/trait with a number of subclasses containing the individual cases. These can be defined in Haskell directly:

data Expr = Value Int | Add Expr Expr | Subtract Expr Expr

this differs from scala in that Value , Add and Subtract are constructors for the Expr type, whereas in Scala the individual case classes also have their own type which can be referenced directly eg

def printValue(v: Value): Unit = { println(v.n) }

As an alternative to what others posted, here's a solution which uses a syntax closer to scala, relying on the small extension GADTSyntax .

{-# LANGUAGE GADTSyntax #-}

--- sealed trait Expr
data Expr where
   -- case class Value(n: Int) extends Expr
   Value :: Int -> Expr
   -- case class Add(e1: Expr, e2: Expr) extends Expr
   Add :: Expr -> Expr -> Expr
   -- case class Subtract(e1: Expr, e2: Expr) extends Expr
   Subtract :: Expr -> Expr -> Expr
data Expr = Value Int | Add Expr Expr | Subtract Expr Expr

https://wiki.haskell.org/Algebraic_data_type

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