Haskell 泛化问题(涉及列表理解)
假设我想知道 (x, y)
平面上位于矩形 has
中的所有点。
我可以使用列表推导式进行计算,如下所示:
let myFun2D = [(x, y) | x <- [0..2], y <- [0..2]]
现在,如果我想对 (x, y, z)
空间完成相同的操作,我可以采用相同的方法并执行
let myFun3D = [(x, y, z) | x <- [0..2], y <- [0..2], z <- [0..2]]
以下操作 :如何将其推广到任意数量的维度?如果是,怎么办?
let myFunGeneralized = ?
谢谢
Let's say I want to know all the points on a (x, y)
plane that are in the rectangle has
.
I can calculate that using List Comprehensions, this way:
let myFun2D = [(x, y) | x <- [0..2], y <- [0..2]]
Now, if I want to accomplish the same for a (x, y, z)
space, I can go the same way and do:
let myFun3D = [(x, y, z) | x <- [0..2], y <- [0..2], z <- [0..2]]
Is there a way to generalize this for any number of dimensions? If yes, how?
let myFunGeneralized = ?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不幸的是,由于
[(a,a)]
和[(a,a,a)]
等属于不同类型,因此您无法编写一个函数来表示所有其中。无论如何,一般来说你可以使用
如果你想要一个
[[a]]
代替,有一个非常简单的函数:or (感谢 sdcvvc)
Unfortunately, because
[(a,a)]
and[(a,a,a)]
etc are of different types, you can't write one function to represent all of them.Anyway, in general you could use
If you want an
[[a]]
instead, there is a very simple function for this:or (thanks sdcvvc)
列表到元组问题可以使用 Template Haskell 来处理,如下所示(运行 ghci -XTemplateHaskell ):
The list to tuple problem could be handled with Template Haskell like this (running
ghci -XTemplateHaskell
):您可以使用这样的内容:
这将为您提供一个点列表列表,您可以假设所有这些子列表都具有相同的长度。它应该像这样工作:
You could use something like this:
This will give you a list of point lists, you can assume that all these sublists have the same length. It should work like this: