【发布时间】:2016-01-03 11:48:15
【问题描述】:
我正在编写二进制搜索实现。我遇到的问题是模式匹配块。
此代码使用模式匹配返回奇怪的结果。第一个匹配块没有返回我所期望的。它警告我永远无法到达(_,_)。
let binSearch (item:double) (arr:list<double>) =
let rec binSearchRec first last =
if first > last then
let lastIndex = arr.Length-1
let len = arr.Length
match (first, last) with
| (0, -1) -> System.String.Format("ITEM SMALLER THAN {0}", arr.[0])
| (len, lastIndex) -> System.String.Format("ITEM BIGGER THAN {0}", arr.[lastIndex])
| (_,_) -> System.String.Format("IN BETWEEN {0} AND {1}", arr.[last], arr.[first])
else
let mid = (first+last)/2
match item.CompareTo(arr.[mid]) with
| -1 -> binSearchRec first (mid-1)
| 0 -> "CONTAINS"
| 1 -> binSearchRec (mid+1) last
binSearchRec 0 (arr.Length-1)
用这个 if-else 替代方法替换第一个 match (first, last) 调用效果很好:
if first = 0 && last = -1 then
System.String.Format("ITEM SMALLER THAN {0}", arr.[0])
else if first = len && last = lastIndex then
System.String.Format("ITEM BIGGER THAN {0}", arr.[lastIndex])
else
System.String.Format("IN BETWEEN {0} AND {1}", arr.[last], arr.[first])
我不明白 match 调用与 if-else 调用有何不同,以及为什么它运行良好但模式匹配块没有。
一个奇怪的结果是在 (len, lastIndex) 匹配中打印 len 在匹配中返回错误的数字。对于长度为 3 的数组,在 match 语句之前打印 len 将显示 3,而在 match 内部打印将显示 1。
【问题讨论】:
标签: f#