haskell how to remove the start word from the expected output

Viewed 75

Am trying to find all possible partitions of a string. For example if i use this single word "sun" ,

`the expected output should be [["su","n"],["s","un"],["s","u","n"]]`

but in my code the output contains the string where the user inputs and i dont want this

        // i dont want ["sun"] in the output 
my output : [["sun"],["su","n"],["s","un"],["s","u","n"]]

Is there any way in my code to stop the function of containing the whole word into the output ? I was thinging to push as input into the auxiliary function the lenght of all partions of the string : length (<function_name> w ) , where w is the string and if the a counter where i will set be equal to length (<function_name> w ) -1 , stop making partitions but i didnt work .

My code is :

partition :: String->[[String]]

partition w =  help_partition w 


help_partition :: String->[[String]]
help_partition [x] = [[[x]]]
help_partition (x:xs) =  [(x:head l):(tail l) | l<- help_partition xs] ++[[x]:l | l<- help_partition xs]
2 Answers

The way your help_partition function works, it will always include the full string as the first element in the returned list, so you can use tail to skip it:

partition w = tail (help_partition w)

or even:

partition = tail . help_partition

This is a pretty common technique: you'll often find yourself writing a recursive function that almost returns the list you want but includes an extra special case as the first or last element, and you can use either tail or init to drop those elements.

You should be able to make your partition function just filter out [w] from the result of help_partition. In other words:

partition w = filter (/= [w]) (help_partition w)
Related