Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell List Comprehensions with Arbitrary number of Generators

Tags:

list

haskell

So what I have so far is something like this:

combs :: [[Char]]
combs = [[i] ++ [j] ++ [k] ++ [l] | i <- x, j <- x, k <- x, l <- x]
  where x = "abc"

So this is the working function for n = 4, is there any way to make this work for an arbitrary number of generators? I could program in for n = 1, 2, 3 etc.. but ideally need it to work for any given n. For reference, x is just an arbitrary string of unique characters. I'm struggling to think of a way to somehow extract it to work for n generators.

like image 330
Stewart Avatar asked Dec 21 '25 14:12

Stewart


1 Answers

You can use replicateM:

replicateM :: Applicative m => Int -> m a -> m [a]

E.g.:

generate :: Num a => Int -> [[a]]
generate = flip replicateM [1,2,3]

to generate all possiible lists of a given length and consisting of elements 1..3.

like image 152
mschmidt Avatar answered Dec 24 '25 10:12

mschmidt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!