Haw Haw
Haw Haw

Reputation: 113

can't get my recursion function to work with a list

Passing in a list such as: [1,2,3,4,5] and get back [ [1,2,3,4,5] , [2,3,4,5] , [3,4,5] , [4,5] , [5] , [] ]

my approach is using recursion to add drop 1 list to another empty list until list is empty. but I can't seem to get my recursion to work correctly.

help please, thanks

my code so far:

test a = test2 a where
test2 a | size(a) > 1 = test (drop 1 a):[]
        | otherwise = []

but that wouldnt work because the recursion is passing back a list in a list, not a list. I just cant figure out how you can assign it to something and return it at the same time.

Upvotes: 0

Views: 151

Answers (4)

Landei
Landei

Reputation: 54584

If you want to go with your drop 1 approach, you could write

test xs = take (1 + length xs) $ iterate (drop 1) xs

A slightly funny version is

import Data.List

test = (++[[]]) . transpose . zipWith replicate [1..]

Upvotes: 1

user946443
user946443

Reputation: 61

fromNet [] = [[]]
fromNet lst =  lst : fromNet (tail lst)

Upvotes: 0

leftaroundabout
leftaroundabout

Reputation: 120711

First of all, what did you do the test a = test2 a for?

Then, you don't need (and shouldn't use) guards for this, do it with pattern matching:

test [] = [[]]
test (a:al) = (a:al):(test al)

If you insist on using guards, you still need do make it actually a list of lists:

test a
  | null a    = [[]]
  | otherwise = a:(test $ tail a)

(Not a list of lists of lists, as I had in my original post...)

Upvotes: 7

hammar
hammar

Reputation: 139850

The function you're describing is already in the standard library, where it's called Data.List.tails. You can have a look at its source code to see how it works.

Upvotes: 6

Related Questions