BBB
BBB

Reputation: 615

Assign Lists/Tuples with do notation

I have a function f that goes something like this:

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

This requires many lines of code and I have a feeling this can be done 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]

Upvotes: 4

Views: 277

Answers (2)

Gabriella Gonzalez
Gabriella Gonzalez

Reputation: 35099

A simpler version of @Zeta's solution is:

import Control.Monad

f = replicateM n g

Upvotes: 7

Zeta
Zeta

Reputation: 105935

Use sequence and replicate:

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

Upvotes: 9

Related Questions