user348307
user348307

Reputation: 21

Generating a list of lists in Haskell

I'm trying to create a function that generates a set of sets of tuples, but I'm new to Haskell and don't know how to implement it. Here's pseudocode of what I'd like my code to do (I'll use {} to denote set):

mySet :: Int -> {{(Int,Int,Int,Int,Int)}}
mySet n = { {a_1,a_2,...,a_n} | P(a_1,a_2,...,a_n) }

The part I've written so far is the list that I'm taking each a_i from. The code is

firstList :: Int -> [(Int,Int,Int,Int,Int)]
firstList n = [(a,b,c,d,e) | a <- [0,1,(-1)], b <- [1..n], c <- [1..(2*n)], d <- [1..n], e <- [1..(2*n)]]

Basically, I want to have mySet take from the list of the form

[(a1,a2,a3,a4,a5),(b1,b2,b3,b4,b5),...]

and create a list (or set, actually) that, for example when n=3, looks like

[[(a1,a2,a3,a4,a5),(b1,b2,b3,b4,b5),(c1,c2,c3,c4,c5)],[(d1,d2,d3,d4,d5),(e1,e2,e3,e4,e5),(f1,f2,f3,f4,f5)],...]

As far as implementations go, I'd prefer readability over speed, but ideally I'd like both.

Upvotes: 1

Views: 983

Answers (1)

CR Drost
CR Drost

Reputation: 9817

You haven't told us precisely how you want to do this, so we're left speculating, but a function that I have defined many times to do a very similar task takes a list of elements and breaks it into sublists of a certain size:

chunkify :: Int -> [x] -> [[x]]
chunkify n [] = []
chunkify n list = chunk : chunkify n rest 
    where (chunk, rest) = splitAt n list

You could then take your 12 n4 tuples coming from firstList n and split them into 12 n3 lists of length n via:

myLists n = chunkify n (firstList n)

Or if you really want to be pointfree, that's just myLists = chunkify <*> firstList because (Int ->) is an instance of a Reader-like applicative functor and the above <*> is defined for applicative functors in Prelude and/or Control.Applicative, depending on what version of GHC you're running.

If you want something more sophisticated you'll have to let us know; we're not mind-readers.

Upvotes: 1

Related Questions