F# - Function with no arguments?

笑着哭i 提交于 2019-12-18 05:27:25

问题


When thinking in a functional mindset, given that functions are supposed to be pure, one can conclude any function with no arguments is basically just a value.
However, reallity gets in the way, and with different inputs, I might not need a certain function, and if that function is computationally expensive, I'd like to not evaluate it if it's not needed.
I found a workaround, using let func _ = ... and calling it with func 1 or whatever, but that feels very non-idiomatic and confusing to the reader.

This boils down to one question: In F#, Is there a proper way to declare a function with zero arguments, without having it evaluated on declaration?


回答1:


The usual idiom is to define the function to take one argument of type Unit (let functionName () = 42). It will then be called as functionName (). (The unit type has only one value, which is ().)




回答2:


I think what you want is lazy.

let resource = 
    lazy(
        // expensive value init here
    )

Then later when you need to read the value...

resource.Value

If you never call the Value property, the code inside the lazy block never gets run, but if you do call it, that code will be run no more than once.



来源:https://stackoverflow.com/questions/2797662/f-function-with-no-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!