Re: Subsets from a set



"stdazi@xxxxxxxxx" <stdazi@xxxxxxxxx> writes:

What i'd like to get is something like this

set A = {2,3,4,5}

subsets(A, 2) returns :

{2,3}, {2,4}, {2,5}, {3,5}, {4,5} .....

In Haskell:

subsets xs 0 = [[]]
subsets [] n | n>0 = []
subsets (x:xs) n | n>0 = map (x:) (subsets xs (n-1)) ++ subsets xs n

Reading guide:

- square brackets are list brackets, so read them like the curly
braces of sets.

- ++ is list concatenation, so read it as U (set union)

- x:xs is the element x added to the list xs, so read it as {x} U xs.

- read "|" as "where".

If you call

subsets [2..5] 2

you get

[[2,3],[2,4],[2,5],[3,4],[3,5],[4,5]].


Torben
.



Relevant Pages

  • Re: MMMWWWAAHHHAHAHAHAHAHAHAAA!!!
    ... >> Martijn van Bilcrosser wrote: ... > change the square brackets for curly braces... ... Capice! ...
    (alt.os.windows-xp)
  • Re: MMMWWWAAHHHAHAHAHAHAHAHAAA!!!
    ... >> indelicate mutual gratification with cadavers, ... change the square brackets for curly braces... ...
    (alt.os.windows-xp)
  • Re: Freedom2surf Service Upgrades
    ... Hence some people use square ... Purpose One: braces within braces. ... programming should round braces be nested. ... quoted missed out the bit in the square brackets, ...
    (comp.sys.acorn.misc)
  • Re: algorithms
    ... The braces in the printf statement is the only thing I really don't ... The square brackets have nothing to do with printf. ... I not quite sure why num2char is a pointer. ...
    (comp.programming)
  • Re: LaTeX question
    ... Braces are curly braces. ... Brackets are square brackets. ... This is an ill-formed array because you have braces around ... % you had seven cells in this row, ...
    (comp.text.tex)