向量维度的编译时检查 [英] Compile-time check for vector dimension

查看:38
本文介绍了向量维度的编译时检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Scala 中实现一些轻量级数学向量.我想使用类型系统在编译时检查向量兼容性.例如,尝试将一个 2 维向量添加到另一个 3 维向量应该会导致编译错误.

I am implementing some lightweight mathematical vectors in scala. I would like to use the type system to check vector compatibility at compile time. For example, trying to add a vector of dimension 2 to another vector of dimension 3 should result in a compile error.

到目前为止,我将维度定义为案例类:

So far, I defined dimensions as case classes:

sealed trait Dim
case class One() extends Dim
case class Two() extends Dim
case class Three() extends Dim
case class Four() extends Dim
case class Five() extends Dim

这里是向量定义:

class Vec[D <: Dim](val values: Vector[Double]) {

  def apply(i: Int) = values(i)

  def *(k: Double) = new Vec[D]( values.map(_*k) )

  def +(that: Vec[D]) = {
    val newValues = ( values zip that.values ) map { 
      pair => pair._1 + pair._2
    }
    new Vec[D](newValues)
  }

  override lazy val toString = "Vec(" + values.mkString(", ") + ")"

}

这个解决方案效果很好,但我有两个问题:

This solution works well, however I have two concerns:

  • 如何添加返回维度的 dimension():Int 方法(即 Vec[Three] 为 3)?

  • How can I add a dimension():Int method that returns the dimension (ie. 3 for a Vec[Three])?

如何在不提前声明所有需要的案例类的情况下处理更高的维度?

How can I handle higher dimensions without declaring all the needed case classes in advance ?

PS:我知道有很好的现有数学向量库,我只是想提高我对 Scala 的理解.

PS: I know there are nice existing mathematical vector libs, I am just trying to improve my scala understanding.

推荐答案

我的建议:

  • Peano Numbers by Apocalysp (link to part a, other parts follow)
  • Church Numerals by Jim McBeath

这篇关于向量维度的编译时检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆