我一直在比较有趣的不同语言的速度执行以下程序:对于i从1到1000000总和产品i*(sqrt i)
我的一个实现(不是唯一的)是构造一个列表[1..1000000],然后用特定的函数折叠.
该程序在Haskell中工作得很好(即使使用foldl而不是foldl'),但在OCaml和F#中堆栈溢出.
这是Haskell代码:
test = foldl (\ a b -> a + b * (sqrt b)) 0
create 0 = []
create n = n:(create (n-1))
main = print (test (create 1000000))
Run Code Online (Sandbox Code Playgroud)
这是OCaml:
let test = List.fold_left (fun a b -> a +. (float_of_int b) *. (sqrt (float_of_int b))) 0. ;;
let rec create = function
| 0 -> []
| n -> n::(create (n-1)) ;;
print_float (test (create 1000000));;
Run Code Online (Sandbox Code Playgroud)
为什么OCaml/F#实现堆栈溢出?