Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All possible sublists as pairs haskell

Tags:

haskell

Bit unsure on how to phrase this properly, so bear with me!

Given a list [1,2,3,4] I want a list of tuples of lists, like so: [([1],[2,3,4]),([1,2],[3,4]),([1,2,3],[4])].

A part B of the question would be to get all possible orderings inside sublists too. So in the case of the first tuple, I'd want the 2 3 4 in the order 243, 324, 432, 423...

Yes, I like non-determinism.

like image 783
Johanna Larsson Avatar asked Dec 27 '22 21:12

Johanna Larsson


1 Answers

import Data.List (inits, tails, permutations)
import Control.Arrow (first, second)

parta :: [a] -> [([a], [a])]
parta [] = []
parta xs = init . tail $ zip (inits xs) (tails xs)

For part b, I'm not sure whether you want [([1],[2,3,4]), ([1],[3,4,2]), ...] or [([1],[[2,3,4],[3,4,2],...]), ...]. If the latter, then

partb :: [a] -> [([a], [[a]])]
partb = map (second permutations) . parta

Edit: Oh, but you want the former. In that case

partb :: [a] -> [([a], [a])]
partb = map (uncurry zip . first repeat . second permutations) . parta

Final edit: As I've already used a couple of functions from Control.Arrow, I'll note that zip (inits xs) (tails xs) can also be written as (inits &&& tails) xs, but I'm not sure it's clearer that way.

like image 191
dave4420 Avatar answered Jan 08 '23 06:01

dave4420