Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

haskell
loops
recursion

Loops in Haskell using recursion

Zain Babar

Overview of loops in Haskell

Haskell is a non-strict language that can handle programs of both a numeric and a symbolic nature. It’s easy to understand and efficient because it has a low compiling time.

Loops in Haskell are implemented using recursion. Since Haskell doesn’t have a built-in function of loops like other languages, we’ll implement a substitute using recursion.

What is recursion?

Recursion is a process in which the function calls itself repeatedly until a base condition set by the programmer is met. Just like loops in any other language, recursion can also get stuck in an infinite loop if the base condition is never satisfied.

Let’s look at an example to better understand the concept of loops in Haskell.

In the following list, let’s replace all the 2’s with 3’s:

[ 1 , 2 , 3 , 2 , 4 , 5 , 2 , 6 ]

Normally in a Python program, we’d use a for loop with a condition to convert the 2’s into 3’s. A sample Python code for this is given below:

def list_edit(list_):
  
  for i in range(len(list_)):
    if list_[i] == 2:
      list_[i] = 3
  print('Changed List: ')
  print(list_)

list_edit([1,2,3,2,4,5,2,6])
Sample Python code

The function above takes in a list and prints a resulting list in which the 2’s have been replaced with 3’s. It uses a for loop for this task.

The same concept applies in a Haskell program. The only difference is that the for loop is replaced with recursion.

A sample Haskell code is given below:

list_edit []=[]
list_edit (x:xs)= if x == 2
                  then 3:list_edit(xs)
                  else x:list_edit(xs)
                  
main=print("Changed List ",list_edit[1, 2 , 3 , 2 , 4 , 5 , 2 , 6 ])
Sample Haskell code

The code above shows a simple loop implementation in Haskell.

  • The line_edit function takes a list and returns a list.
  • Line 1: This is the base case of the recursion. It says that if an empty list is passed to the function, it should return an empty list and the function shouldn’t call itself again.
  • Line 2: We take in a list and separate it into two parts. x:xs divides the list into a head—which is denoted by the variable x—and the rest of the body, which is denoted by the variable xs.
  • The program then goes on and checks if the head is equal to the integer 2. If it is, then it adds the integer 3 with the rest of the body. Before the replacement of 2 with 3, the rest of the body is sent to the function itself to check if there are any other 2’s present.
  • If the head isn’t equal to 2, the program simply adds the head to the rest of the body after it is checked through recursion.

RELATED TAGS

haskell
loops
recursion
RELATED COURSES

View all Courses

Keep Exploring