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.
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...)
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.
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..]
fromNet [] = [[]]
fromNet lst = lst : fromNet (tail lst)
精彩评论