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.
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] .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With