如何建模一个点? [英] How to model a point?
问题描述
我正在尝试使用 x 和 y 坐标对一个点进行建模.我想以这样一种方式来做到这一点,即不可能混淆 x 和 y 值.
I'm trying to model a point with x and y coordinates. I'd like to do it in such a way as to make it impossible to mix up the x and y values.
所以,我想出了这个:
package com.craigtreptow.scrayz
package object types {
type X = Double
type Y = Double
type Point = (X,Y)
}
然后我像这样使用它:
package com.craigtreptow.scrayz.types
object Main extends App {
val x: X = 1.1
val y: Y = 2.2
val p: Point = (x, x)
println(p)
}
我预计这会产生错误,但它奏效了:
I expected that to produce an error, but it worked:
~/c/scrayz(master|✚2…)> sbt run
[info] Loading project definition from /Users/Ctreptow/code/scrayz/project
[info] Loading settings for project scrayz from build.sbt ...
[info] Set current project to Scrayz (in build file:/Users/Ctreptow/code/scrayz/)
[info] running com.craigtreptow.scrayz.types.Main
(1.1,1.1)
[success] Total time: 1 s, completed Mar 9, 2020 6:08:49 PM
是否可以像这样对 Point
进行建模,使得上述代码会产生编译器错误?
Is it possible to model a Point
like this, such that the above code would produce a compiler error?
推荐答案
注意给定
type X = Double
type Y = Double
我们有X = Y
,即它们是等价类型.也许将每个坐标包装成自己的类型
we have X = Y
, that is, they are equivalent types. Perhaps wrap each coordinate in its own type
final case class X(v: Double) extends AnyVal
object X {
implicit def doubleToX(x: Double): X = X(x)
}
final case class Y(v: Double) extends AnyVal
object Y {
implicit def doubleToY(y: Double): Y = Y(y)
}
final case class Point(x: X, y: Y)
val x: X = 1.1
val y: Y = 2.2
val p: Point = Point(x, x) // Error: type mismatch; found: X required: Y
注意 case class X(v: Double)
如何将 double 包装到 specialised 语义上下文中,我们知道这个 double 表示 X 轴坐标,而不是 general 纯双,可以有多种含义.类似的推理适用于将点建模为案例类而不是纯元组.
Note how case class X(v: Double)
wraps the double into specialised semantic context where we know this double means X-axis coordinate, as opposed to general pure double which could take any number of meanings. Similar reasoning holds for modelling point as case class as opposed to pure tuple.
这篇关于如何建模一个点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!