Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension: making lists of lists

hi im trying to make a function in haskell that takes a number a makes a partion of it using lists i.e. for number 4 it would create [[1,1,1,1],[1,1,2],[1,3],[2,2],[4]]. I was thinking of using list comprehension for this where it would create list x and then create further lists using numbers from [1...n] (n being the partition number I would want) where the sum of the list created would be equal to n.

The code I have created so far is-

partions (n:xs) = [[x|x<-[1...n], sum[x]==n]]|xs<-[1..]]

but obiviously it doesnt work, any suggestions?

thanks.

like image 570
dave Avatar asked Nov 16 '10 17:11

dave


People also ask

How do you flatten a list of lists with a list comprehension?

To flatten a list of lists, use the list comprehension statement [x for l in lst for x in l] . To modify all elements in a list of lists (e.g., increment them by one), use a list comprehension of list comprehensions [[x+1 for x in l] for l in lst] .

Does list comprehension creates a new list?

List comprehensions are used for creating new lists from other iterables. As list comprehensions return lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element.

How do I make a list list comprehension?

List comprehension is an elegant way to define and create lists based on existing lists. List comprehension is generally more compact and faster than normal functions and loops for creating list. However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.


1 Answers

I suggest trying recursion: To obtain the partitions of n, iterate over the numbers i = 1 to n, and recursively generate the partitions of (n-i), the base case being that the only partition of 1 is 1 itself, and the partition of 0 is the empty list.

like image 71
Lagerbaer Avatar answered Oct 05 '22 11:10

Lagerbaer