Comments and Style
Prerequisites: Defining functions
Comments
-- A single-line comment
{- A block comment
spanning several lines.
{- Block comments can nest. -} -}
-- | Returns the price including tax.
--
-- >>> withTax 100
-- 120.0
withTax :: Double -> Double
withTax price = price * 1.2 -- after code
main :: IO ()
main = print (withTax 100)
120.0
Comments starting with -- | are Haddock documentation comments:
the haddock tool (and cabal haddock) turns them into HTML docs, and
your editor shows them on hover. The >>> lines are examples that the
doctest tool can run as tests.
Style guidelines
Common conventions in the Haskell community:
- A type signature on every top-level definition.
camelCasefor functions and values,PascalCasefor types, constructors, type classes, and modules.- Two-space (or four-space) indentation; spaces, never tabs (GHC warns about tabs).
- Short names for very local, generic values (
x,xs,f,acc), descriptive names for everything else. Thessuffix means "plural":(x : xs). - Small functions that do one thing, composed together.
- Pattern matching and
Maybeinstead ofhead,tail,fromJust, and!!. - Compile with
-Walland fix the warnings.
Tools
- Ormolu / Fourmolu — format code automatically.
- HLint — suggests simplifications, for example
concat (map f xs)→concatMap f xs. - Haskell Language Server — types on hover, errors as you type, and one-click HLint fixes.
What's next
You now know the core of Haskell: types, functions, lists, pattern matching, and recursion. Try the Beginner Projects, then continue to Level 2 — Intermediate, which starts with higher-order functions and goes on to your own data types, type classes, and monads.