Writing Functions

In this lesson, we will write our first Haskell functions.

Basic function syntax

Let’s look at a simple example of a Haskell function that concatenates a string with itself:

Press + to interact
sayTwice :: String -> String
sayTwice s = s ++ s
main = print (sayTwice "hello")

The first line is a type annotation for our function sayTwice. It has the form:

function_name :: argument_type -> return_type

Type annotations are actually optional, as GHC can also infer the type automatically. But, it is usually helpful to add type annotations to functions as

  • They can serve as documentation and will make the code easier to understand.
  • They can help the compiler to generate better error messages if we make a type error when writing our functions.

The second line is an equation that defines our function. It says that the input argument s should be concatenated with itself. The equation must immediately follow the type annotation if there is one.

Equations for functions with one argument have the form:

 ...