Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Generator with variable number of inputs?

at the moment my code looks a bit like this:

gen (x:[]) = [[a] | a <- (someOp x)]
gen (x:y:[]) = [[a,b] | a <- (someOp x), b <- (someOp y)]
gen (x:y:z:[]) = [[a,b,c] | a <- (someOp x), b <- (someOp y), c <- (someOp z)]

... and so on

is it possible to conclude the rest with gen(x:xs) ??

like image 527
manwingbb Avatar asked Jan 17 '26 23:01

manwingbb


2 Answers

You can do this recursively:

gen [] = [[]]
gen (x:xs) = [ a:g | a <- someOp x, g <- gen xs ]

At each step you take all the lists generated by the previous step and combine each of them with every result of someOp.

You can verify that this degrades into your special cases by substitution.

like image 155
Fyodor Soikin Avatar answered Jan 21 '26 00:01

Fyodor Soikin


For the function you here construct, a more generic function already exists: traverse :: (Applicative f, Traversable t) => (a -> f b) -> t a -> f (t b). Your gen is equivalent to:

gen = traverse someOp
like image 44
Willem Van Onsem Avatar answered Jan 21 '26 02:01

Willem Van Onsem



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!