Write a function from IO a -> a?

后端 未结 4 850
野的像风
野的像风 2021-01-22 17:57

Take the function getLine.

it has a type

getLine :: IO String

How do I extract the String from this IO value. More generally, how do I

4条回答
  •  情深已故
    2021-01-22 18:25

    So "generally", it's unclear why you think you need a function of this type and in this case it makes all the difference.

    It should be noted for completeness that it is possible. There indeed exists a function of type IO a -> a in the base library called unsafePerformIO.

    But the unsafe part is there for a reason. There are few situations where its usage would be considered justified. It's an escape hatch to be used with great caution - most of the time you will let monsters in instead of letting yourself out.

    Why can't you normally go from IO a to a? Well at the very least it allows you to break the rules by having a seemingly pure function that is not pure at all - ouch! If it were a common practice to do this the type signatures and all the work done by the compiler to verify them would make no sense at all. All the correctness guarantees would go out of the window.

    Haskell is, partly, interesting precisely because this is (normally) impossible.

    For how to approach your getLine problem in particular see the other answers.

提交回复
热议问题