Split a set in Haskell

I am trying to write a Haskell program that can return a set of sections of a user-defined set. A partition of the set S is defined as the set of nonempty, pairwise disjoint subsets of S, the union of which S. So, [1,2,3]returns [[[2],[3,1]],[[2,1],[3]],[[3,2,1]],[[1],[3,2]],[[1],[2],[3]]]. I think I can use another program that I wrote some time ago that finds a Cartesian product from two sets. So [1,2,3] ['a', 'b']returns [(1,'a'),(1,'b'),(2,'a'),(2,'b'),(3,'a'),(3,'b')]. However, I'm not quite sure how to do this. I think this will require recursion, though, if it can even be adapted correctly. Here is the code for the subset:

type Set a = [a]

isElement :: Eq a => a -> [a] -> Bool
isElement x [] = False
isElement x (y:ys) = if(x==y) then True else isElement x ys

subset :: Eq a => Set a -> Set a -> Bool
subset [] xs = True
subset (y:ys) xs = if(isElement y xs == True)
                  then do subset ys xs
                  else do False
+4
source share
2 answers

, X ∪ {x} X. x ( x , x ..) .

:

partitions :: [a] -> [[[a]]]
partitions [] = [[]]
partitions (x:xs) = expand x $ partitions xs where

    expand :: a -> [[[a]]] -> [[[a]]]
    expand x ys = concatMap (extend x) ys

    extend :: a -> [[a]] -> [[[a]]]
    extend x [] = [[[x]]]
    extend x (y:ys) = ((x:y):ys) : map (y:) (extend x ys)

: https://ideone.com/ClYOoQ

+6

:

If |S| = 1
  Return 
Otherwise
  For each nonempty proper subset X ⊂ S
    Let Y = S - X
    Add {X, Y} to R
    For each Z in {partitionSet(X)}
      Add Z ∪ {Y} to R.
  Return R

"" , concatMap . R . Haskell Data.List.subsequences.

S, , , . , X > Y, {X, Y}, {Y, X} {X, Y, Z}, {Y, X, Z}. , !

S, ⋃Z = X X ∪ Y = S, Z Y S, S, subpartition , .

{X, SX}, , X. i > 2 {a_1, a_2,..., a_i}, {a_1, a_2} - {a_1 ⋃ a_2} {{a_1 ⋃ a_2},..., a_i} - i-1 parent node . S.

+1

Source: https://habr.com/ru/post/1686990/


All Articles