F#图形绘制代码编译报FS0010模式匹配不完整构造错误求助
F# 绘图代码编译报错修复方案
报错原因说明
你遇到的FS0010报错是makePicture函数内的match表达式语法完全不符合F#规范导致的,同时代码还存在多处语法疏漏,全部问题如下:
- match语句结构错误:
match ImgUtil.getPixel n C with colorAt n x写法不合法,F#中match ... with后必须跟|开头的匹配分支,不能直接写函数调用 figTest定义错误:组合两种图形需要使用你自定义的Mix构造器,不能直接并列两个图形构造语句- 多处语法符号遗漏:Rectangle构造参数之间缺少逗号、函数调用参数之间缺少逗号、ImgUtil类名大小写错误
- 循环逻辑错误:F#不支持直接遍历二维点范围,需要嵌套循环遍历x、y坐标;循环边界错误会导致数组越界
- 函数作用域错误:保存图片的代码缩进不对,不属于
makePicture函数作用域
修复后的完整代码
#r "path/to/ImgUtil.dll" // 请替换为你本地ImgUtil.dll的实际路径 type point = int * int type color = ImgUtil.color type figure = | Circle of point * int * color | Rectangle of point * point * color | Mix of figure * figure let rec colorAt (x,y) figure = match figure with | Circle ((cx,cy), r, col) -> if (x-cx)*(x-cx)+(y-cy)*(y-cy) <= r*r then Some col else None | Rectangle ((x0,y0), (x1,y1), col) -> if x0 <=x && x <= x1 && y0 <= y && y <= y1 then Some col else None | Mix (f1, f2) -> match (colorAt (x,y) f1, colorAt (x,y) f2) with |(None , c) -> c |(c, None) -> c |(Some c1, Some c2) -> let (a1 ,r1 ,g1 ,b1) = ImgUtil.fromColor c1 let (a2 ,r2 ,g2 ,b2) = ImgUtil.fromColor c2 Some(ImgUtil.fromArgb ((a1+a2)/2, (r1+r2)/2, (g1+g2)/2, (b1+b2)/2)) // 用Mix组合圆形和矩形,补全参数逗号 let figTest : figure = Mix( Circle ((50,50), 45, ImgUtil.fromRgb(255,0,0)), Rectangle ((40,40), (90,110), ImgUtil.fromRgb (0,0,255)) ) // 修正参数定义,优化参数名避免歧义 let makePicture (name:string, figure:figure, width:int, height:int) : unit = let img = ImgUtil.mk width height // 绘制灰色背景,修正边界避免越界 for y = 0 to height - 1 do ImgUtil.setLine (ImgUtil.fromRgb(128,128,128)) (0,y) (width - 1,y) img // 嵌套循环遍历所有坐标点 for x = 0 to width - 1 do for y = 0 to height - 1 do match colorAt (x,y) figure with | Some col -> ImgUtil.setPixel col (x,y) img | None -> () // 无匹配颜色保留背景灰色 // 修正类名大小写,输出文件 ImgUtil.toPngFile name img // 补全参数逗号,调用生成图片 makePicture ("figTest.png", figTest, 101, 151)
使用说明
把代码第一行的dll路径替换为你本地编译好的ImgUtil.dll的实际路径,运行即可在同级目录下生成名为figTest.png的图片。
内容的提问来源于stack exchange,提问作者Stadsbjerg
相关产品推荐
相关产品推荐

