Search code examples
haskellrecursionlist-comprehension

extracting the first element of a tuple via list comprehension in haskell


I tried to extract the first element of a tuple in a list of tuples in haskell via list comprehension but somehow it just outputs the first one and then stops, so I decided to do it via recursion which looked like this:

tuples :: (Ord a, Ord b) => [(a, b)] -> [a]
tuples [] = []
tuples ((x,y):xs) = x : tuples xs

Now, while this works I would like to know how to do the same thing via list comprehension.


Solution

  • Yes, you can use pattern matching in the list comprehension, with:

    tuples :: [(a, b)] -> [a]
    tuples xs = [ x | (x, _) <- xs ]

    But likely the simplest way is just to work with fst :: (a, b) -> a:

    tuples :: [(a, b)] -> [a]
    tuples = map fst

    The typeconstraints for (Ord a, Ord b) are not necessary: nowhere do we use a function defined for types that are members of the Ord typeclass.