在 Haskell Where 子句中定义自己的数据类型
Defining Own Data Type in Haskell Where clause
data Geometry = Point {xCoord:: Double
,yCoord:: Double} |Line {xCoeff:: Double
,yCoeff:: Double
,constant:: Double}|Plane {xCoeff:: Double,yCoeff:: Double,
zCoeff::Double,
constant::Double} deriving (Show)
intersection:: Geometry -> Geometry -> Either String Geometry
intersection (Line a1 b1 c1) (Line a2 b2 c2)
| #### some code
intersection (Plane a1 b1 c1 d1) (Plane a2 b2 c2 d2)
| #### some code
| n1_n2_z /= 0 = Right $ParamerticLine (Point3D t1 (cond12/n1_n2_z) 0) (Point3D n1_n2_x n1_n2_y n1_n2_z)
| otherwise ## some code
where {Point t1 t2 = intersection (Line a1 b1 d1) (Line a2 b2 d2)}
我正在尝试在条件 n1_n2_z/=0 中计算平面交点的 where 子句中的线交点并使用 t1。我收到 where 子句的错误。我可以使用 where 子句中定义的交集函数吗?我在 where 子句中做错了什么?
失败的原因是因为 intersect
具有签名:
intersection:: Geometry -> Geometry -> <b>Either String Geometry</b>
但是您的 where
子句的左侧显示:
where <b>Point</b> t1 t2 = intersection (Line a1 b1 d1) (Line a2 b2 d2)
所以这里你的左操作数的类型是 Geometry
,而不是 Either String Geometry
。
您应该将其捕获为:
where <b>Right (</b>Point t1 t2<b>)</b> = intersection (Line a1 b1 d1) (Line a2 b2 d2)
但这是不安全的,因为这可能是左"some error message"。因此,您可能希望在此处使用 pattern guard [Haskell-wiki]:
# …
intersection (Plane a1 b1 c1 d1) (Plane a2 b2 c2 d2)
| … = …
| n1_n2_z /= 0, <b>Right (Point t1 t2) <-</b> intersection (Line a1 b1 d1) (Line a2 b2 d2) = Right $ ParamerticLine (Point3D t1 (cond12/n1_n2_z) 0) (Point3D n1_n2_x n1_n2_y n1_n2_z)
| otherwise = …
或者您可以查看 Monad (Either a)
实现,然后使用绑定来处理这样的 Either a
。
data Geometry = Point {xCoord:: Double
,yCoord:: Double} |Line {xCoeff:: Double
,yCoeff:: Double
,constant:: Double}|Plane {xCoeff:: Double,yCoeff:: Double,
zCoeff::Double,
constant::Double} deriving (Show)
intersection:: Geometry -> Geometry -> Either String Geometry
intersection (Line a1 b1 c1) (Line a2 b2 c2)
| #### some code
intersection (Plane a1 b1 c1 d1) (Plane a2 b2 c2 d2)
| #### some code
| n1_n2_z /= 0 = Right $ParamerticLine (Point3D t1 (cond12/n1_n2_z) 0) (Point3D n1_n2_x n1_n2_y n1_n2_z)
| otherwise ## some code
where {Point t1 t2 = intersection (Line a1 b1 d1) (Line a2 b2 d2)}
我正在尝试在条件 n1_n2_z/=0 中计算平面交点的 where 子句中的线交点并使用 t1。我收到 where 子句的错误。我可以使用 where 子句中定义的交集函数吗?我在 where 子句中做错了什么?
失败的原因是因为 intersect
具有签名:
intersection:: Geometry -> Geometry -> <b>Either String Geometry</b>
但是您的 where
子句的左侧显示:
where <b>Point</b> t1 t2 = intersection (Line a1 b1 d1) (Line a2 b2 d2)
所以这里你的左操作数的类型是 Geometry
,而不是 Either String Geometry
。
您应该将其捕获为:
where <b>Right (</b>Point t1 t2<b>)</b> = intersection (Line a1 b1 d1) (Line a2 b2 d2)
但这是不安全的,因为这可能是左"some error message"。因此,您可能希望在此处使用 pattern guard [Haskell-wiki]:
# …
intersection (Plane a1 b1 c1 d1) (Plane a2 b2 c2 d2)
| … = …
| n1_n2_z /= 0, <b>Right (Point t1 t2) <-</b> intersection (Line a1 b1 d1) (Line a2 b2 d2) = Right $ ParamerticLine (Point3D t1 (cond12/n1_n2_z) 0) (Point3D n1_n2_x n1_n2_y n1_n2_z)
| otherwise = …
或者您可以查看 Monad (Either a)
实现,然后使用绑定来处理这样的 Either a
。