2013-11-27 79 views
1

这是一个F#关闭。代码示例由another questionF#关闭中的懒惰评估

let isPasswordBetter (newPassword:string) (currPassword:string) = 

    let isLongEnough = newPassword.Length > 1 

    let newIsLongerThanCurrent = 
     (newPassword.Length > currPassword.Length) 

    if isLongEnough then 
     if newIsLongerThanCurrent then 
      true 
     else 
      false 
    else 
     false 

let result1 = isPasswordBetter "a" "hello" 
let result2 = isPasswordBetter "hellothere" "hello" 
let result3 = isPasswordBetter "aaa" "hello" 

启发假设一分钟即newIsLongerThanCurrent计算量非常大。

如果我理解正确F# is lazy by default,这意味着newIsLongerThanCurrent将在进入if than之前总是评估,即使其评估可能不必要。因此,我应该明确地使其成为lazy

我的理解是否正确?我宁愿避免混乱的代码,如果lazy是没有必要推迟计算newIsLongerThanCurrent

+0

谢谢大家的帮助,是的,F#是**不按默认值**懒.. – NoIdeaHowToFixThis

回答

2

F#是not默认情况下懒惰。地说,F#是懒默认

if isLongEnough then 
    if newIsLongerThanCurrent() then 
... 
3

尤金是正确的: 最懒的“懒惰”的方法是转换newIsLongerThanCurrent的功能:

let newIsLongerThanCurrent() = 
    (newPassword.Length > currPassword.Length) 

,并应用它在if -clause 。在这种情况下,将newIsLongerThanCurrent变成函数是最好的方法。

一般来说,F#提供了一种使用lazy关键字添加懒惰的方法。如果您需要多次访问该值(因为它缓存结果,而多次运行某个函数则会重复运行计算),这非常有用。

let newIsLongerThanCurrent = 
    lazy (newPassword.Length > currPassword.Length) 

if isLongEnough then 
    if newIsLongerThanCurrent.Value then    // Computation evaluated here 
     let x = newIsLongerThanCurrent.Value || other // ..the result is reused here 
     (...) 
+0

我不认为类型相当在您的示例的指点工作了... – kvb

+0

@kvb谢谢出。固定。 –