Haskell: recursive function on sets

I'm new to Haskell, and I'm trying to write a (somewhat) basic recursive function that generates set sections. I refer to this wiki page ( https://en.wikipedia.org/wiki/Partition_of_a_set ) for my definition of the given sections.

I currently have a function that produces most, but not all, sections:

separate :: [a] -> [[[a]]]
separate [] = [[]]
separate (b:bs) = [[b]:s | s <- separate bs] ++ [(b:qs):qss | (qs:qss) <- separate bs]

>separate [1,2,3]
[[[1],[2],[3]],[[1],[2,3]],[[1,2],[3]],[[1,2,3]]]

As you can see, there is no option [[1,3],[2]].

I was wondering if it is easy to change this function to meet my requirements or to create a whole new function. Thanks.

+4
source share
1 answer

, [(b:qs):qss | (qs:qss) <- separate bs] b bs. .

separate (b:bs) = [[b]:s | s <- separate bs]
               ++ (singleModifies (b:) =<< separate bs)

-- | All possibilities of applying a function to exactly one element in the list.
singleModifies :: (a->a) -> [a] -> [[a]]
singleModifies _ [] = []
singleModifies f (x:xs) = (f x:xs) : map (x:) (singleModifies f xs) 

, =<<: "" . separate bs ; singleModifies, , , join (aka concat) .

separate (b:bs) = [[b]:s | s <- separate bs]
               ++ concat [singleModifies (b:) bp | bp <- separate bs]
+3

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


All Articles