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.
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])
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 ])
The code above shows a simple loop implementation in Haskell.
line_editfunction takes a list and returns a list.
x:xsdivides the list into a head—which is denoted by the variable
x—and the rest of the body, which is denoted by the variable
2. If it is, then it adds the integer
3with 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.
2, the program simply adds the head to the rest of the body after it is checked through recursion.
View all Courses