F#中使用List.filter筛选机器人候选位置时代码报错求助
问题分析与解决
错误原因
- 候选点生成逻辑错误:代码里硬编码使用全局变量
p1生成相邻点,而非函数参数src,导致无论传入什么源点,都只会生成(1,1)的相邻位置,完全不符合函数的通用性要求。 - 类型不匹配错误:
List.filter中的判断条件x <= dist p1 p2存在类型冲突——x是pos(int*int)类型,而dist返回int类型,F#不允许直接比较不同类型的值。需要计算候选点到目标点的距离,再和源点到目标点的距离做数值比较。
修正后的代码
type pos = int*int let p1 = (1, 1) // source grid point let p2 = (3, 3) // target grid point // 已实现的距离函数 let dist (p1: pos) (p2: pos) : int = pown (fst p2 - fst p1) 2 + pown (snd p2 - snd p1) 2 // 修正后的candidates函数 let candidates (src: pos) (tg: pos) : pos list = let x, y = src // 解构源点坐标 // 根据传入的src生成四个相邻点 let candi = [(x+1, y); (x-1, y); (x, y+1); (x, y-1)] let srcToTgDist = dist src tg // 提前计算源点到目标点的距离,避免重复计算 // 过滤出符合距离要求的候选点 candi |> List.filter (fun candidate -> dist candidate tg <= srcToTgDist) // 测试 printfn "%A" (dist p1 p2) printfn "%A" (candidates p1 p2)
关键修正说明
- 用
let x, y = src解构源点坐标,简洁生成相邻点,同时确保使用函数传入的src参数,而非全局变量。 - 提前计算
srcToTgDist,避免在List.filter中重复调用距离函数,提升执行效率。 - 在
filter逻辑中,正确计算每个候选点到目标点的距离,再与源点到目标点的距离做数值比较,彻底解决类型不匹配问题。
内容的提问来源于stack exchange,提问作者Hoodwinked
相关产品推荐
相关产品推荐

