Assign lists / tuples with a designation

I have a f function that looks something like this:

f = do
      x1 <- g
      x2 <- g
      x3 <- g
      ...
      xn <- g
      return [x1,x2,x3,..., xn] --or (x1,x2,x3,..., xn)

It takes a lot of lines of code, and I feel that it can be prettier. I would like to know if there is a way to do something like this:

f = do
      [x,y,z] <- [g,g,g]
      return [x,y,z]
+4
source share
2 answers

Use sequenceand replicate:

f = do
    xs <- sequence $ replicate n g
    return xs
+9
source

The simplest version of @Zeta's solution:

import Control.Monad

f = replicateM n g
+7
source

All Articles