Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for list construction / concatenation

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.

like image 248
Colin Woodbury Avatar asked Apr 13 '11 12:04

Colin Woodbury


People also ask

How do you concatenate a list in Python?

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.

How do you concatenate lists in Haskell?

(++) makes a new list that is the concatenation of two lists.

How do you concatenate two lists of strings in Python?

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 do you mean by concatenation in list explain with 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] .


1 Answers

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.

like image 89
Jeff Foster Avatar answered Sep 22 '22 09:09

Jeff Foster