How can a time function exist in functional programming?

后端 未结 15 520
Happy的楠姐
Happy的楠姐 2020-12-04 04:26

I\'ve to admit that I don\'t know much about functional programming. I read about it from here and there, and so came to know that in functional programming, a function retu

15条回答
  •  醉酒成梦
    2020-12-04 05:04

    It can be answered without introducing other concepts of FP.

    Possibility 1: time as function argument

    A language consists of

    1. language core and
    2. standard library.

    Referential transparency is a property of language core, but not standard library. By no means is it a property of programs written in that language.

    Using OP's notation, should one have a function

    f(t) = t*v0 + x0; // mathematical function that knows current time
    

    They would ask standard library to get current time, say 1.23, and compute the function with that value as an argument f(1.23) (or just 1.23*v0 + x0, referential transparency!). That way the code gets to know the current time.

    Possibility 2: time as return value

    Answering OP's question:

    Can a time function (which returns the current time) exist in functional programming?

    Yes, but that function has to have an argument and you would have to compute it with different inputs so it returns different current time, otherwise it would violate the principals of FP.

    f(s) = t(s)*v0 + x0; // mathematical function t(s) returns current time
    

    This is an alternative approach to what I've described above. But then again, the question of obtaining those different inputs s in the first place still comes down to standard library.

    Possibility 3: functional reactive programming

    The idea is that function t() evaluates to current time paired with function t2. When one needs current time again later they are to call t2(), it will then give function t3 and so on

    (x, t2) = t(); // it's x o'clock now
    ...
    (x2, t3) = t2(); // now it's already x2 o'clock
    ...
    t(); x; // both evaluate to the initial time, referential transparency!
    

    There's more to FP but I believe it's out of the scope of OP. For example, how does one ask standard library to compute a function and act upon its return value in purely functional way: that one is rather about side effects than referential transparency.

提交回复
热议问题