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:

-- Using let in GHCi
let x = 5

-- Direct definition in a script
x = 5

Explanation:

  • let x = 5 assigns the value 5 to the variable x.
  • In a script, you can directly write x = 5 without the let keyword.

Practical Example:

-- Define variables
a = 10
b = 20

-- Use variables in an expression
sum = a + b

Exercise:

Define two variables, m and n, with values 15 and 25 respectively, and calculate their product.

-- Your code here

Solution:

m = 15
n = 25
product = m * n

Functions

Defining Functions

Functions in Haskell are defined using the following syntax:

functionName :: Type -> Type -> ... -> ReturnType
functionName parameter1 parameter2 ... = expression

Example:

-- Function to add two numbers
add :: Int -> Int -> Int
add x y = x + y

Explanation:

  • add :: Int -> Int -> Int specifies that add is a function that takes two Int arguments and returns an Int.
  • add x y = x + y defines the function body, where x and y 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.

-- Your code here

Solution:

subtract :: Int -> Int -> Int
subtract x y = x - y

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 the square function to the argument 5, resulting in 25.

Exercise:

Define a function cube that takes an integer and returns its cube. Then, apply this function to the number 3.

-- Your code here

Solution:

cube :: Int -> Int
cube x = x * x * x

-- Applying the function
result = cube 3

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.

© Copyright 2024. All rights reserved