How can a time function exist in functional programming ?
No function can obtain the current time since it is continuosly changing. Assume that getClockTime is a constant that gets the current time. This action in constant.Let us say that print is a function. Function calls do not have side effects in a pure functional language, we instead imagine that it is a action of printing it to the console. To print the time to the console one has to combine the two actions. The getClockTime cannot be passed to print, since print expects a timestamp. But there is an operator, >>=, to combine the two actions, one which gets a timestamp, and one which takes one as argument and prints it. Applying this a new action can print the current time. And this is incidentally exactly how it is done in Haskell
Prelude> System.Time.getClockTime >>= print Fri Sep 2 01:13:23 東京 (標準時) 2011
This function is pure since it does not perform any IO operations.The action is same but the results are different.
The side effects of a function can be handles by monad function in haskell.Monad has some values and functions in it.Suppose the type is,
data IO a = IO (RealWorld -> (a,RealWorld))
The above code can implement the IO actions safely. IO action is a function, that has a token of type RealWorld and gives a new token and a result.The most used function in Monad is bind >>=.
(>>=) :: IO a -> (a -> IO b) -> IO b
The function bind >>= inputs one action and a function and creates a new result based on this action.Suppose there is a string now :: IOString, where the current time is represented as a string.To print it one can use the function putStrLn:
now >>= putStrLn
One can also use the do function,
do currTime <- now putStrLn currTime
We can map the information of the world outside the RealWorld. The RealWorld token is different.Therefore everytime output is different but input remains the same.