Thursday, July 9, 2009

Side effects and message

So far, we thought of a function as a blackbox which takes in some number of input arguments and returns a particular output. However, this type of a function is not very useful for programming computers as, in computer systems you have to open a file, close file, and do other similar things that are unrelated to the process of taking inputs and returning the output.Seeing things from a functional perspective, programming computers involves allowing for and performing a lot of side effects.There are functions that have side effects to perform various tasks such as printing onto the screen, opening and closing files, and so on.
The message function not only takes in its arguments and returns the formatted string but it also does something more by printing the output onto the screen. It is different from the way that other functions print out on the screen because what the other functions print is their return value but the message function prints the formatted string onto the screen no matter what and also returns the printed string.

I hope that the example code given below will help you understand the string manipulation functions concat, substring, message more clearly.

Code :
  1. (concat)
  2. (substring "This is an example" 1)
  3. (substring "This is an example" 1 4)
  4. (message (concat "Hi " " emacs-lisper!\n" " Welcome Aboard!"))
  5. (message "The quick brown foxes jumped over the lazy dog.")
  6. (concat (message "Hi !") "How are you?")
  7. (message "%s How are you?" (concat "Hi !"))

The programs in the 6th and 7th lines return the same answer but the manner in which they do is different.

Code :
  (concat (message "Hi !") "How are you?")

The above program returns "Hi ! How are you?" and so does the code below :
Code :
 (message "%s How are you?" (concat "Hi !"))

Yet, there is a difference in the output of the two codes. Can you see how they are different?

Well, in order to see the difference I will suggest you do the following.
  • Evaluate the first code, and then type in C-x b, type *Messages* and then press enter
    • Notice the last two lines
  • Now, evaluate the next code and again type C-x b, type *Messages* and then press enter
    • Again, notice the last two lines

P.S.:- If you are still puzzled then try executing the following code and comparing the contents of the *Messages* buffer
Code :
(message "hi from message")
(concat "hi from concat") 


Anonymous said...

C-h e gets you to the messages buffer even quicker ;).

Abdullah Abdul Khadir said...

You're right !!!
"C-h e runs the command view-echo-area-messages
which is an interactive compiled Lisp function in `help.el'.
It is bound to C-h e, <f1> e, <help> e.

Post a Comment