代数数据类型 scala 定义构造函数

问题描述

我是使用 Scala 的代数数据类型的新手,我有一个问题:

我想定义二进制类型,二进制数由一串“0”和“1”表示,所以我需要3个构造函数一个表示空值,一个表示零,另一个表示1。

正如我们所知,在代数数据类型中,1 是 0 的后继,我们可以这样写

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

我的问题是如何将其定义为案例类

等待您的回复

提前致谢

解决方法

您所描述的内容通常被称为“Peano 数字”。

这是一个实现。

abstract class Nat    //"Nat" for natural numbers
class _0 extends Nat  //or you can use "zero" here
class Succ[N <: Nat] extends Nat

这就是你真正需要的。随着所表示的值越来越高,将其全部写出来变得更加麻烦,Succ[Succ[Succ[_0]]],但这就是类型别名派上用场的地方。

type _1 = Succ[_0]
type _2 = Succ[_1]
type _3 = Succ[_2]
type _4 = Succ[_3]
type _5 = Succ[_4]

转换为 case 类可能如下所示:

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.