How can a time function exist in functional programming?

后端 未结 15 517
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:02

    If yes, then how can it exist? Does it not violate the principle of functional programming? It particularly violates referential transparency

    It does not exist in a purely functional sense.

    Or if no, then how can one know the current time in functional programming?

    It may first be useful to know how a time is retrieved on a computer. Essentially there is onboard circuitry that keeps track of the time (which is the reason a computer would usually need a small cell battery). Then there might be some internal process that sets the value of time at a certain memory register. Which essentially boils down to a value that can be retrieved by the CPU.


    For Haskell, there is a concept of an 'IO action' which represents a type that can be made to carry out some IO process. So instead of referencing a time value we reference a IO Time value. All this would be purely functional. We aren't referencing time but something along the lines of 'read the value of the time register'.

    When we actually execute the Haskell program, the IO action would actually take place.

提交回复
热议问题