【发布时间】:2018-11-26 15:32:35
【问题描述】:
我目前正在开发一个简单的程序,它返回包含两个图形的最小矩形的两个点 (int * int)(一个圆和另一个矩形,定义为 box 和 circ,如下所示)。到目前为止,我的程序是这样的:
type point = int * int // a point (x, y) in the plane
type colour = int * int * int // (red , green , blue ), 0..255
type name = string
type figure =
| Circle of point * int * colour
// defined by center , radius , and colour
| Rectangle of point * point * colour
// defined by corners bottom -left , top -right , and colour
| Mix of figure * figure
// combine figures with mixed colour at overlap
// finds colour of figure at point
let rec colourAt (x ,y) figure =
match figure with
| Circle ((cx, cy), r, col) ->
if (x-cx)*(x-cx)+(y-cy)*(y-cy) <= r*r
// uses Pythagoras ' equation to determine
// distance to centers
then Some col else None
| Rectangle ((x0,y0), (x1,y1), col) ->
if x0 <= x && x <= x1 && y0 <= y && y <= y1
// within corners
then Some col else None
| Mix (f1,f2) ->
match ( colourAt (x , y) f1 , colourAt (x ,y ) f2 ) with
| (None, c) -> c // no overlap
| (c, None ) -> c // no overlap
| (Some (r1,g1,b1), Some (r2,g2,b2)) ->
// average color
Some ((r1+r2)/2, (g1+g2)/2, (b1+b2)/2)
(以上都是为程序预定义的,我的代码如下所示) (请不要介意在程序的其他子部分中使用的颜色、颜色等类型,它们已经像魅力一样工作了)
let box = Rectangle ((40,40),(90,110),(0,0,255))
let circ = Circle ((50,50),45,(255,0,0))
let figTest = Mix(box,circ)
let rec boundingBox figure : point * point =
match figure with
| Circle ((cx,cy), r, col) -> (point(cx-r,cy-r),point(cx+r,cy+r))
| Rectangle ((x0,y0), (x1,y1), col) -> (point(x0,y0),point(x1,y1))
| Mix(f1,f2) ->
let (p1,p2) = boundingBox(f1)
let (p3,p4) = boundingBox(f2)
let p5 = (min((fst p1),(fst p3)),min((snd p1),(snd p3)))
let p6 = (max((fst p2),(fst p4)),max((snd p2),(snd p4)))
p5,p6
printfn "Mix figTest --> %A" (boundingBox figTest)
printfn "Rectangle box --> %A" (boundingBox box)
printfn "Circle circ --> %A" (boundingBox circ)
我的程序的问题是我的 p5,p6 从 Mix(f1,f2) 上的模式匹配返回的值不断给我一个类型错误说:
类型“int”与类型int * int -> int * int不匹配
我非常有信心,否则代码对于所需的功能应该是正确的。
但是,我的程序预计会产生一个点 * 点(其中点 = int * int)。谁能看到我错过了什么?我可以在 box 和 circle 上运行我的程序,这会产生正确的结果:
对于 circ = (5,5) (95,95) 对于框 = (40,40) (90,110)
我最后一个包含 (circ,box) 的 figTest 因此应该返回 min(5,40),min(40,5) = (5,5) 和 max(90,95),max(95,110) = ( 95,110) 加起来为 (5,5) (95,110),这是我对 Mix(f1,f2) 的预期结果,但由于上述类型错误而无法读取。
我错过了什么?我通常在我的 F# 编码中遇到类型错误(这似乎只是通过在 F# 中进行学习的一部分),但我似乎能够以某种方式修复它,但这个只是不会无论我尝试什么,都要屈服。
谢谢。
【问题讨论】:
标签: types f# syntax-error typeerror