用符号分配列表/元组 [英] Assign Lists/Tuples with do notation

查看:72
本文介绍了用符号分配列表/元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数f,如下所示:

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]


推荐答案

使用 sequence replicate

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

这篇关于用符号分配列表/元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆