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 show
used to convert an int
value to string
.
The syntax of this method is: show n
, where n
represents 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:
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 show
method, then concatenate them and return back the concatenated value.
Lines 6–7: Declare two integer values.
Line 9: Invoke the function concatTwoIntToStr
previously defined and store the result in a variable named result
.
Line 10: Print out the string result.
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 show
method, then concatenate them and return back the concatenated value. The read
function is applied to convert the result from a string to a number.
Lines 6–7: Declare two integer values.
Line 9: Invoke the function concatTwoIntToInt
previously defined and store the result in a variable named result
.
Line 10: Print out the result while using the show
method to convert the integer result to a string.
Free Resources