Reputation: 11
I'm new to algebraic data type using scala and I have a question:
I want to define type binary, a binary number is presented by a string of "0" & "1" so I need 3 constructors, one to represent the value null, one for the zero and the other for the one.
As we know in algebraic data type a one is a successor of zero and we can write like this
one = suc(zero)
two = suc(one)
trait Binary
case class zero extends from Binary // the null value
case class Suc(n: Binary) extends from Binary // the string "0"
// here I need to have the constructor of the number one but I don't know how to do it
case class Suc(Suc(n) : Binary) extends from Binary// but it doesn't seem logic to me
my problem is how to define the one as a case class
waiting for you responses,
thanks in advance
Upvotes: 1
Views: 223
Reputation: 51271
What you're describing is often referred to as "Peano numbers."
Here's one implementation.
abstract class Nat //"Nat" for natural numbers
class _0 extends Nat //or you can use "zero" here
class Succ[N <: Nat] extends Nat
And that's all you really need. As the values being represented get higher it becomes more cumbersome to write it all out, Succ[Succ[Succ[_0]]]
, but that's where type aliases come in handy.
type _1 = Succ[_0]
type _2 = Succ[_1]
type _3 = Succ[_2]
type _4 = Succ[_3]
type _5 = Succ[_4]
Translating into case
classes might look something like this:
trait Binary
case object Zero extends Binary
case class Suc(n: Binary) extends Binary
val one = Suc(Zero)
val two = Suc(one) //Suc(Suc(Zero))
// etc.
Upvotes: 2