Writing Functions
Explore how to write basic Haskell functions by using type annotations and pattern matching. Understand the syntax and significance of specifying types, and practice running your functions in the ghci interpreter. This lesson helps you grasp how to create clear, type-safe functions and execute them effectively.
We'll cover the following...
Basic function syntax
Let’s look at a simple example of a Haskell function that concatenates a string with itself:
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:
function_name pattern = expression
The most common form of patterns is a pattern variable, in this case s. Pattern variables always ...