Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 212
Freewind Avatar asked Aug 01 '15 10:08

Freewind


3 Answers

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 e.g.

def printValue(v: Value): Unit = { println(v.n) }
like image 142
Lee Avatar answered Nov 17 '22 00:11

Lee


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
like image 6
chi Avatar answered Nov 17 '22 01:11

chi


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

https://wiki.haskell.org/Algebraic_data_type

like image 3
dmitry Avatar answered Nov 17 '22 00:11

dmitry