我可以以一种简洁的方式计算立方体列表吗?
可以用高阶函数、Monad 或其他什么来简化以下函数吗?
cube list = [(x, y, z) | x <- list, y <- list, z <- list]
该函数只是创建列表元素的所有三重排列的列表。例如:
> cube [1..2]
[(1,1,1),(1,1,2),(1,2,1),(1,2,2),(2,1,1),(2,1,2),(2,2,1),(2,2,2)]
Can the following function be simplified with higher order functions, Monads or what have you?
cube list = [(x, y, z) | x <- list, y <- list, z <- list]
The function simply creates a list of all triple-permutations of the elements of the list. For example:
> cube [1..2]
[(1,1,1),(1,1,2),(1,2,1),(1,2,2),(2,1,1),(2,1,2),(2,2,1),(2,2,2)]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
从比尔的回答来看,因为这是使用列表单子的代码,所以我们可以使用“应用程序”风格来“使用高阶函数”。这是否是一个好主意留给工程师作为练习。
Going from Bill's answer, because this is code uses the list monad, we can use "applicative" style to do "with higher-order functions". Whether or not this is a good idea is left as an exercise for the engineer.
尽管它为您提供列表而不是元组,但您可以使用 Control.Monad:
sequence
函数很简洁,因为尽管它的“预期”目的是获取操作列表,按顺序执行它们,并在列表中返回其结果,在列表中使用它 monad 可以免费为您提供组合。Although it gives you lists instead of tuples, you can use the
sequence
function in Control.Monad:The
sequence
function is neat because, although its "intended" purpose is to take a list of actions, do them in order, and return their results in a list, using it on the list monad gives you combinations for free.事实上,您的列表理解是 List monad 的一种用法。
另一种写法是:
In fact, your list comprehension is a usage of the List monad.
Another way to write this is:
这并不是一个严肃的答案,但无论如何我必须建议它。主要是为了疯狂。
和那个人玩得开心吧。 :)
This isn't really a serious answer, but I have to suggest it anyway. Mostly for the sake of craziness.
Have fun with that one. :)
为了模仿 Joey Adams 所做的事情:
对于完整的解决方案(传递一个列表并获取 3 元组),可以这样做:
但是恕我直言,Edward Z. Yang 的解决方案占据主导地位。
To model after what Joey Adams did:
For the full solution(pass it a list and get 3-tuples), something like this can be done:
But IMHO, Edward Z. Yang's solution reigns supreme.
如果你可以拥有位,谁还需要单子?
Who needs monads if you can have bits?