James Elkwood
James Elkwood

Reputation: 155

Haskell function that returns sublists of a list

I'm writing a function in Haskell that, when given a list of numbers, will return a list containing all sublists (in order) of that original list. What I have so far is:

sublists [] = [[]]
sublists (x:xs) = [x:sublist | sublist <- sublists xs] ++ sublists xs

The above code, if given [1,2,3], returns [[1,2,3],[1,2],[1,3],[1],[2,3],[2],[3],[]], which is not quite what I am looking for. Instead the function should return:

[[1],[1,2],[1,2,3]]

How do I modify the given code to get this result?

Upvotes: 1

Views: 1783

Answers (1)

Henri Menke
Henri Menke

Reputation: 10939

Why don't you take the first n elements from the list for n between 1 and the length of the input?

sublists :: [a] -> [[a]]
sublists xs = [ take n xs | n <- [1..length xs] ]
> sublists [1,2,3]
[[1],[1,2],[1,2,3]]

Alternatively using recursion and pattern matching

sublists' :: [a] -> [[a]]
sublists' xs = sublist [] xs where
    sublist a [b] = [ a ++ [b] ]
    sublist a (b:bs) = [ a ++ [b] ] ++ sublist (a ++ [b]) bs

Upvotes: 1

Related Questions