I've only been at Haskell for two days now, and was wondering what the difference between the two function definitions below are:
Prelude> let swap (x1:x2:xs) = x2:x1:xs
Prelude> swap [1..5]
[2,1,3,4,5]
Prelude> let swap' (x1:x2:xs) = [x2] ++ [x1] ++ xs
Prelude> swap' [1..5]
[2,1,3,4,5]
That is, what makes x2:x1:xs different from [x2] ++ [x1] ++ xs ? Please and thanks.
1. Concatenation operator (+) for List Concatenation. The '+' operator can be used to concatenate two lists. It appends one list at the end of the other list and results in a new list as output.
(++) makes a new list that is the concatenation of two lists.
The most conventional method to concatenate lists in python is by using the concatenation operator(+). The “+” operator can easily join the whole list behind another list and provide you with the new list as the final output as shown in the below example.
What Is Concatenation? Concatenation of lists is an operation where the elements of one list are added at the end of another list. For example, if we have a list with elements [1, 2, 3] and another list with elements [4, 5, 6] .
The type signatures are a good place to start:
(:) :: a -> [a] -> [a]
(++) :: [a] -> [a] -> [a]
You can find these out with :type (:)
and :type (++)
in ghci.
As you can see from the type signatures, both are used to produce lists.
The :
operator is used to construct lists (and to take them apart again for pattern matching). To make a list [1,2,3]
you just build it up with 1 : 2 : 3 : []
. The first element of :
is the item to add on the front of the list, and the second element is either a list (also built up with :
or the empty list signified by []
).
The ++
operator is list concatenation. It takes two lists and appends them together. [1,2,3] ++ [4,5,6]
is legal, whereas 1 ++ [1,2,3]
is not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With