In this section, we will cover the basics of variables and functions in Haskell. Understanding these concepts is crucial as they form the foundation of any Haskell program. We will explore how to define variables, create functions, and use them effectively.
Variables
Defining Variables
In Haskell, variables are immutable, meaning once a value is assigned to a variable, it cannot be changed. Variables are defined using the let
keyword or directly in a function definition.
Example:
Explanation:
let x = 5
assigns the value5
to the variablex
.- In a script, you can directly write
x = 5
without thelet
keyword.
Practical Example:
Exercise:
Define two variables, m
and n
, with values 15
and 25
respectively, and calculate their product.
Solution:
Functions
Defining Functions
Functions in Haskell are defined using the following syntax:
functionName :: Type -> Type -> ... -> ReturnType functionName parameter1 parameter2 ... = expression
Example:
Explanation:
add :: Int -> Int -> Int
specifies thatadd
is a function that takes twoInt
arguments and returns anInt
.add x y = x + y
defines the function body, wherex
andy
are parameters.
Practical Example:
-- Function to multiply two numbers multiply :: Int -> Int -> Int multiply x y = x * y -- Using the function result = multiply 3 4
Exercise:
Define a function subtract
that takes two integers and returns their difference.
Solution:
Function Application
In Haskell, functions are applied by simply writing the function name followed by its arguments.
Example:
-- Function to square a number square :: Int -> Int square x = x * x -- Applying the function result = square 5
Explanation:
square 5
applies thesquare
function to the argument5
, resulting in25
.
Exercise:
Define a function cube
that takes an integer and returns its cube. Then, apply this function to the number 3
.
Solution:
Summary
In this section, we covered the basics of variables and functions in Haskell. We learned how to define immutable variables, create functions, and apply them. These concepts are fundamental to writing Haskell programs and will be used extensively in subsequent modules.
Next, we will explore basic data types in Haskell, which will help us understand how to work with different kinds of data in our programs.
Haskell Programming Course
Module 1: Introduction to Haskell
- What is Haskell?
- Setting Up the Haskell Environment
- Basic Syntax and Hello World
- Haskell REPL (GHCi)