Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is print in Haskell a pure function?

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.

like image 358
bubu Avatar asked Nov 16 '17 17:11

bubu


People also ask

Are all functions in Haskell pure?

Haskell is a functional programming language, in which (almost) all expressions are pure; thus, Haskell is a purely functional programming language. Excellent.

What is a pure function Haskell?

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.

Why is print an impure function?

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.

What is purity in Haskell?

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.


2 Answers

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 Ints 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
like image 108
danidiaz Avatar answered Sep 21 '22 22:09

danidiaz


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.

like image 28
jcarpenter2 Avatar answered Sep 25 '22 22:09

jcarpenter2