F.A
F.A

Reputation: 317

How to count how many elements are in a list?

I know about the length function, but if I have a list such as [(1,2),(2,3),(3,4)] and try to use length it does not work. I tried to concatenate but that doesn't help. Any idea how?

Upvotes: 2

Views: 3582

Answers (2)

duplode
duplode

Reputation: 34378

While the sensible solution to your immediate problem is (2 *) . length, as 9000 pointed out, it is worth dwelling a bit on why length [(1,2),(2,3),(3,4)] doesn't do what you expect. A Haskell list contains an arbitrary number of elements of the same type. A Haskell pair, however, has exactly two elements of possibly different types, which is something quite different and which is not implicitly converted into a list (see this question for further discussion of that point). However, nothing stops us from writing a conversion function ourselves:

pairToList :: (a, a) -> [a]
pairToList (x, y) = [x, y]

Note that the argument of pairToList is of type (a, a); that is, the function only accepts pairs with both elements having the same type.

Given pairToList, we can convert the pairs in your list...

GHCi> map pairToList [(1,2),(2,3),(3,4)]
[[1,2],[2,3],[3,4]]

... and then proceed as you planned originally:

GHCi> (length . concat . map pairToList) [(1,2),(2,3),(3,4)]
6

The concatMap function combines map and concat into a single pass...

GHCi> :t concatMap
concatMap :: Foldable t => (a -> [b]) -> t a -> [b]

... and so your function becomes simply:

GHCi> (length . concatMap pairToList) [(1,2),(2,3),(3,4)]
6

Upvotes: 6

nburk
nburk

Reputation: 22731

length [(1,2),(2,3),(3,4)] gives you 3 because there are precisely three elements in the list where the elements are tuples, each consisting of two integers. use this function to get all the "elements"

tupleLength :: [(Int, Int)] -> Int
tupleLength = (*2) . length

Upvotes: 4

Related Questions