Why is it possible to sleep / pause execution in Haskell if it's purely functional?

后端 未结 3 1569
挽巷
挽巷 2021-02-01 04:31

I saw Haskell has a sleep function called \"delay\": Control.Concurrent.Thread.Delay

My question is: if Haskell is purely functional, how is it possible to have

3条回答
  •  轮回少年
    2021-02-01 05:16

    "Purely functional" is a interesting term.

    Everything that needs to deal with the real world isn't purely functional at the first look. But somehow Haskell needs to deal with the real world. Otherwise the language wouldn't make sense.

    So the solution is the IO monad. I won't go into much detail here (I'm sure you can find another explanation of the IO monad). The IO monad is roughly a function with the type RealWorld -> RealWorld.

    That means that instead of doing something outside of our program, we pretend the real world would be part of our program and every time we want to change something in the real world, we create another real world that we like more.

    The trick with delay is that we take the current world and create another one where the time is advanced the given amount of seconds.

提交回复
热议问题