F#中的递归函数与递归变量 [英] Recursive function vs recursive variable in F#
问题描述
第一种方法是好的. 第二个不断重复相同的数字对.
The first method is OK. The second repeats constantly the same pair of numbers.
对我来说,这是个很晦涩的原因……你能指出一个好的方向吗?
It is quite obscure to me why... Could you point to the good direction ?
module Normal =
let rnd = new MersenneTwister()
let sampleNormal =
fun () -> let rec randomNormal() = let u1, u2 = rnd.NextDouble(),rnd.NextDouble()
let r, theta= sqrt (-2. * (log u1)), 2. * System.Math.PI * u2
seq { yield r * sin theta; yield r * cos theta ; printfn "next";yield! randomNormal() }
randomNormal()
let sampleNormalBAD =
fun () -> let rec randomNormal = let u1, u2 = rnd.NextDouble(),rnd.NextDouble()
let r, theta= sqrt (-2. * (log u1)), 2. * System.Math.PI * u2
seq { yield r * sin theta; yield r * cos theta ; printfn "next";yield! randomNormal }
randomNormal
Normal.sampleNormal() |> Seq.take(10) |>Seq.toArray
Normal.sampleNormalBAD() |> Seq.take(10) |>Seq.toArray
推荐答案
在第一个示例中,randomNormal()
是一个函数,它使用()
并返回一个值,每次都会对其进行求值.
在第二个中,randomNormal
是一个值,因此不会被两次求值,一旦受限制,它将保持相同的值.
In the first sample randomNormal()
is a function, it takes ()
and return a value, it will be evaluated each time.
In the second one randomNormal
is a value, so it will not be evaluated twice, once bounded it will remain with the same value.
如果将鼠标悬停在randomNormal()
上,签名是:
If you rollover randomNormal()
the signature is :
unit->seq<float>
,对于randomNormal
只是:
seq<float>
更新:因为printfn
在序列的内部(有界值),所以它继续打印.
如果您尝试在最后一行之前在正文中进行打印,则会看到不同之处.这是一个简化的示例代码:
UPDATE: It keeps printing because the printfn
is inside the sequence, which is the bounded value.
If you try printing in the body before the last line you will see the difference. Here's a simplified sample code:
let sampleNormal =
fun () ->
let rec randomNormal() =
let u1, u2 = 1,2
printfn "Evaluating"
seq { yield u1; yield u2 ; printfn "next";yield! randomNormal() }
randomNormal()
let sampleNormalBAD =
fun () ->
let rec randomNormal =
let u1, u2 = 1,2
printfn "Evaluating"
seq { yield u1; yield u2 ; printfn "next";yield! randomNormal }
randomNormal
这篇关于F#中的递归函数与递归变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!