Personal tools


From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
(do not repeat Haskell report)
m (pretty 'clear')

Latest revision as of 23:20, 14 March 2011

It is generally a good idea to write comprehensible programs, and adding comments to your program can help to achieve that goal. However it is not true that every program can be become comprehensible by adding enough comments. In the first place you should write as clearly as possible such that comments are not necessary. Comments cannot be checked by the compiler and thus they tend to diverge from actual implementation. If you are going to write a comment, think about the following items before you actually write it:

  • Is it a comment that documents unexpected behaviour? Then better avoid the unexpected behaviour. Example:
a+b-b  -- you cannot delete (b-b) because the operations are not associative

If the operations are not associative for your custom type,

then better do not define a
instance for it. (Sure,
types are not ideal.)

I repeat: Try hard - very hard - preferably repeatedly - to remove unexpected behaviour from your program. Comments can never fix unexpected behaviour.

  • Is it an obvious comment? Example:
-- swap the elements of a pair
swap :: (a,b) -> (b,a)

Congratulations: You have chosen a function name and a type signature that make the purpose of the function pretty clear without any comment. Thus: omit the comment, you only risk that it becomes out of sync with the function.

  • Does the comment duplicate the Haskell report?
let b=a+1   -- add one to 'a'
The meaning of
should be clear from the Haskell report.

You may better comment the intention of your code like in

let b=a+1   -- increase the loop counter 'a'

But again, writing programs that do not require comments is the better choice. E.g.

let newCounter = oldCounter+1

[edit] See also