Is print
in Haskell a pure function; why or why not? I'm thinking it's not, because it does not always return the same value as pure functions should.
Haskell is a functional programming language, in which (almost) all expressions are pure; thus, Haskell is a purely functional programming language. Excellent.
From HaskellWiki. A function is called pure if it corresponds to a function in the mathematical sense: it associates each possible input value with an output value, and does nothing else.
printf is impure because its result has "side effects" -- specifically, it prints something on the screen (or in a file, etc). If it were pure, then you could call it a billion times and be sure nothing bad would happen.
Haskell can do anything your mainstream programming language can. Purity is not about preventing side effects (a database query or an http request), it's about having a clear boundary between code with side effects (impure) and pure code.
A value of type IO Int
is not really an Int
. It's more like a piece of paper which reads "hey Haskell runtime, please produce an Int
value in such and such way". The piece of paper is inert and remains the same, even if the Int
s eventually produced by the runtime are different.
You send the piece of paper to the runtime by assigning it to main
. If the IO
action never comes in the way of main
and instead languishes inside some container, it will never get executed.
Functions that return IO
actions are pure like the others. They always return the same piece of paper. What the runtime does with those instructions is another matter.
If they weren't pure, we would have to think twice before changing
foo :: (Int -> IO Int) -> IO Int
foo f = liftA2 (+) (f 0) (f 0)
to:
foo :: (Int -> IO Int) -> IO Int
foo f = let x = f 0 in liftA2 (+) x x
Yes, print
is a pure function. The value it returns has type IO ()
, which you can think of as a bunch of code that outputs the string you passed in. For each string you pass in, it always returns the same code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With