Search code examples
haskellfunctional-programming

A function that takes a list and returns the same list but without the duplicates


So as the title says I'm supposed to make a function that takes a list and returns the list without the duplicates, but I can't use list comprehensions, only high-order functions and lambdas.

I've found this code from another users question.

has :: (Eq a) => [a] -> a -> Bool
has [] _ = False
has (x:xs) a
  | x == a    = True
  | otherwise = has xs a

unique :: (Eq a) => [a] -> [a]
unique [] = []
unique (x:xs)
  | has xs x  = unique xs
  | otherwise = x : unique xs

I understand how it works, but I don't understand how I could do the same thing with high-order fuctions. I'm new to Haskell so any tips would be appreciated.


Solution

  • but I can't use list comprehensions, only high-order functions and lambdas.

    The good news is: you don't use list comprehensions.

    You can work with foldr :: (a -> b -> b) -> b -> [a] -> b here. Here the first function takes an element of type a and the "result" of the function of the rest of the list (so here the unique list of elements of the remaining elements). Your function thus should check if the element already appears in that result. You thus can implement this with:

    unique :: Eq a => [a] -> [a]
    unique = foldr f []
        where f x xs
                | … = …
                | otherwise = …

    where you still need to fill in the parts. You can even generalize this to any Foldable:

    unique :: (Eq a, Foldable f) => f a -> [a]
    unique = foldr f []
        where f x xs
                | … = …
                | otherwise = …