How to concatenate two integers in Haskell
Haskell is a statically typed, functional, and concurrent programming language with a dynamic range of packages.
We might come across situations entailing the concatenation of two integer values. In this scenario, we can use the following methods:
Concatenating integers as strings
Concatenating integers as integers
To concatenate two integer values in Haskell, the easiest way will be to convert both values to a string and then concatenate them using the Haskell concatenation operators.
This process involves:
The method
showused to convert anintvalue tostring.
The syntax of this method is:show n, wherenrepresents the integer value to be converted.The operator (
<>or++) used for concatenating the converted string values, as follows:result = s1 <> s2 or result = s1 ++ s2
Let's go through the following examples for a better understanding of these methods:
Concatenating integers as strings
This example illustrates how to concatenate two integer values and return a string output:
concatTwoIntToStr :: Int -> Int -> StringconcatTwoIntToStr n1 n2 = ((show n1) ++ (show n2))main :: IO ()main = dolet a = 42b = 45putStr "The result is: "let result = concatTwoIntToStr a bputStr (result)
Let's go over the code widget above:
Lines 1–2: Define a function that accepts two integer parameters, convert them to a string using the
showmethod, then concatenate them and return back the concatenated value.Lines 6–7: Declare two integer values.
Line 9: Invoke the function
concatTwoIntToStrpreviously defined and store the result in a variable namedresult.Line 10: Print out the string result.
Concatenating integers as integers
This example illustrates how to concatenate two integer values and return an integer value as output:
concatTwoIntToInt :: Int -> Int -> IntconcatTwoIntToInt n1 n2 = read ((show n1) ++ (show n2))main :: IO ()main = dolet a = 42b = 45putStr "The result is: "let result = concatTwoIntToInt a bputStr (show result)
Let's go over the code widget above:
Lines 1–2: Define a function that accepts two integer parameters, convert them to a string using the
showmethod, then concatenate them and return back the concatenated value. Thereadfunction is applied to convert the result from a string to a number.Lines 6–7: Declare two integer values.
Line 9: Invoke the function
concatTwoIntToIntpreviously defined and store the result in a variable namedresult.Line 10: Print out the result while using the
showmethod to convert the integer result to a string.
Free Resources