Haskell Program to Swap Two Numbers


This tutorial discusses writing a program to swap two numbers in the Haskell programming language.

Variables are immutable in Haskell i.e once declared their values cannot be changed. So we cannot swap the values of two variables, but we can mimic this by swapping values in a list and tuple.

In this tutorial we see,

  • Program to swap two numbers in a binary tuple.
  • Program to swap two numbers in a list.

In Haskell, tuples are used to store elements of different data types as a collection. Tuples are identified by parenthesis at the ends. Tuples support only a few functions. Multiple tuples cannot be combined or merged. For example, a tuple looks like (“john”,24).

A binary tuple is a tuple having only two elements.

In Haskell, a list is a data structure used to store a list of elements of the same data type.

Lists are identified with square brackets at the ends. List support many functions in Haskell. Multiple lists can be combined to make a new list. For example, a list looks like [1,3,2] is a list of numbers.

Algorithm Steps

  • Initialize list or tuple.
  • Implement program logic to swap two numbers in a list or tuple.
  • Print the resultant list or tuple.

Example 1

Program to swap two numbers in a binary tuple.

-- function definition
swap (a,b) = (b,a)
main :: IO()
main = do
-- declaring and initializing tuple
   let tup = (21,"john")
-- invoking the function swap
   let revtup = swap tup
-- printing the reversed tuple
   print ("The resultant tuple after the swap is:")
   print (revtup)

Output

"The resultant tuple after the swap is:"
("john",21)

In the above program, we defined a function swap as such it takes two arguments as a tuple a,b and the function returns the binary tuple by swapping their positions. This function takes a binary tuple as an argument and returns a tuple by swapping the elements. In the main function, we initialized a tuple with an integer value of 21 and a string value of “john”. We invoked the function swap with this initialized tuple as an argument and loaded the returned output into a variable revtup. Finally, printed the resultant tuple after the swap using the print function.

Example 2

Program to swap two numbers in a list

swapHelper :: [Int]->Int->Int->[Int]
-- function definition
swapHelper xs a b = swap xs a b (xs!!a) (xs!!b)

-- function declaration
swap :: [Int]->Int->Int->Int->Int->[Int]

-- function definition
swap [] a b e1 e2 = []
swap (x:xs) a b e1 e2 = if(a==0)
   then [e2] ++ (swap xs (a-1) (b-1) e1 e2)
   else if (b==0)
      then [e1] ++ (swap xs (a-1) (b-1) e1 e2)
      else [x] ++ (swap xs (a-1) (b-1) e1 e2)
      
main :: IO()
main = do
-- declaring and initializing list indices
   let list = [1,2,3,4]
   let a = 0
   let b = 1
-- invoking the function swapHelper
   let revlist = swapHelper list 0 1
-- printing the resultant list
   print ("The resultant list after swapping elements at indices " ++ show a ++ "," ++ show b ++ " in the list " ++ show list ++ " is:" )
   print (revlist)

Output

"The resultant list after swapping elements at indices 0,1 in the list [1,2,3,4] is:"
[2,1,3,4]

In the above program,

We declared a function swaphelper as such it takes a list of integers and two integer arguments and returns a list of integers. In its function definition, the function takes a list of integers xs and two integers a, and b as arguments. The function swap is invoked with arguments xs, a, b, and elements in xs which are at indices a and b in the list of integers xs.

The elements at an index in a list can be retrieved using an infix function “!!”. The syntax is LIST !! INDEX. For example this code xs!!2 returns the element at index 2 in the list xs.

We declared a function swap as such it takes a list of integers as an argument, four integer arguments, and returns a list of integers. In its function definition, it accepts arguments for a list of integers xs using pattern matching by destructuring the list as (x:xs) where x is the first element in the list and xs the rest of the list. It accepts four integer arguments a, b, e1, and e2. Where a and b are indices of the elements to be replaced. e1 and e2 are the actual values of the elements to be replaced.

In the function, The value of the a is checked if the value of the a is zero, the control is transferred to the then block where the function recursively calls itself with arguments remaining list xs, a-1, b-1, e1, and e2, preconcatenated with the single integer list [e2]. If the value of a is not equal to zero then the control is transferred to the else block, where the value of b is checked.

If the value of b is zero, the control is transferred to the then block where the function recursively calls itself with arguments remaining list xs, a-1, b-1, e1, and e2, concatenated with the single integer list [e1].

If the value of b is not equal to zero then the control is transferred to the else block, where the function recursively calls itself with arguments remaining list xs, a-1, b-1, e1, and e2, concatenated with the single integer list [x]. Where x is the first element in the list argument.

The function swap reverses the elements in a list at the given indices. Where the swapHelper is a helper function that finds the elements at that indices and invokes the swap function.

In the main function, a list of integers is initialized with the index variables a, and b. The function swap helper is invoked and the returned output is loaded into a variable revlist. Finally, the resultant list is printed using the print function.

Conclusion

In this tutorial, we discussed implementing a program to swap elements in a list and binary tuple in the Haskell programming language.

Updated on: 14-Dec-2022

631 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements