繁体   English   中英

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

[英]Algebraic Data type scala define constructors

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

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

正如我们在代数数据类型中所知道的,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

我的问题是如何定义一个案例 class

等你回复,

提前致谢

您所描述的通常被称为“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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM