Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `print <$> (print "hello")` print "hello"?

Tags:

haskell

When calculating IO (IO ()), both (IO ()) and () is calculated, so why

main :: IO (IO ())
main = print <$> (print "Hello, World!")

print

"Hello, World!"

not

IO "Hello, World!" -- ??
"Hello, World!"
like image 905
q e x y Avatar asked Oct 21 '19 11:10

q e x y


People also ask

What is the output of print print Hello?

printf() is a library function to send formatted output to the screen. In this program, printf() displays Hello, World! text on the screen. The return 0; statement is the "Exit status" of the program.

What does print mean in code?

In many programming languages, print is a function that sends text, variables, or another object to the screen. If you're more familiar with the programming language Scratch, print is equivalent to say.

What is the difference between hello and hello in Python?

Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello".

What does print Hello, World mean in Python?

In Python 3, programming a “Hello World” message is as easy as typing print('Hello World') into the Python console: >>> print('Hello World') Hello World. Note that single and double quotes may be used interchangeably in Python.


1 Answers

main :: IO (IO ())
main = print <$> (print "Hello, World!")

is equivalent, thanks to the monad laws, to

main :: IO (IO ())
main = do 
   result <- print "Hello, World!"
   return (print result)

Now, print always returns () as result, so the whole code is equivalent to

main :: IO (IO ())
main = do 
   _ <- print "Hello, World!"
   return (print ())

Finally, the result of main is simply discarded. That is, the last line could be return (putStrLn "this is ignored") and have the same effect.

Hence the code will only execute the first print "Hello, World!".

I would recommend that you always define main :: IO (). Haskell allows us to declare main :: IO AnyTypeHere, but this is (IMO) confusing.

I would also recommend you use putStrLn, and not print to print strings, since the latter will quote and escape the whole string.

like image 192
chi Avatar answered Oct 09 '22 05:10

chi