【发布时间】:2013-01-08 03:43:22
【问题描述】:
我正在阅读一篇博文: http://flyingfrogblog.blogspot.com/2009/07/ocaml-vs-f-burrows-wheeler.html
Burrow Wheeler 压缩算法的简单实现:
# compare two strings str[i..end,0..i-1] and str[j..end,0..j-1]
let cmp (str: _ array) i j =
let rec cmp i j =
if i=str.Length then 1 else
if j=str.Length then -1 else
let c = compare str.[i] str.[j] in
if c<>0 then c else
cmp (i+1) (j+1)
cmp i j
# sort n strings
let bwt (str: byte array) =
let n = str.Length
let a = Array.init n (fun i -> i)
Array.sortInPlaceWith (cmp str) a
Array.init n (fun i -> str.[(a.[i] + n - 1) % n])
这个实现看起来很高效,但实际上很慢,因为排序Array.sortInPlaceWith (cmp str) a 使用了一个闭包函数(cmp str),并且调用它的次数太多(平均为O(n log n))!
通过将排序算法内联和比较函数内联,速度快。
我的问题是,内联函数是否意味着看似闭包的调用不再是闭包?
我在想的另一件事是 C 中的函数指针。当我们使用 qsort 时:
void qsort ( void * base, size_t num, size_t size, int ( * comparator ) ( const void *, const void * ) );
我们需要传入一个比较函数的指针。似乎在 C 的情况下,速度并没有太多。
谢谢!
【问题讨论】:
标签: .net f# functional-programming