Haskell泛化问题(涉及列表解析) [英] Haskell generalizing problem (involving list comprehensions)
问题描述
中的(x,y)
平面上的所有点都有$ c $
我可以用这种方式计算出使用List Comprehensions:
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 =?
谢谢
解决方案不幸的是,因为 [(a,a)]
和 [(a,a,a)]
等是不同的类型,你不能写一个函数来表示它们。
无论如何,一般来说,您可以使用
Prelude>让x = [0..2]
Prelude> import Control.Applicative
Prelude Control.Applicative> (,,)< $> x * x * x
[(0,0,0),(0,0,1),(0,0,2),(0,1,0),(0,1,1),(0,1 ,2),(0,2,0),(0,2,1),(0,2,2),(1,0,0),(1,0,1),(1,0,2 ),(1,1,0),(1,1,1),(1,1,2),(1,2,0),(1,2,1),(1,2,2), (2,0,0),(2,0,1),(2,0,2),(2,1,0),(2,1,1),(2,1,2),(2 ,2,0),(2,2,1),(2,2,2)]
如果你想要一个 [[a]]
,这里有一个非常简单的函数:
前奏>序列(复制3 x)
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1] ,[0,1,2],[0,2,0],[0,2,1],[0,2,2],[1,0,0],[1,0,1],[ 1,0,2],[1,1,0],[1,1,1],[1,1,2],[1,2,0],[1,2,1],[1, 2,2],[2,0,0],[2,0,1],[2,0,2],[2,1,0],[2,1,1],[2,1, 2],[2,2,0],[2,2,1],[2,2,2]]
或(谢谢sdcvvc)
Prelude>导入Control.Monad
Prelude Control.Monad> replicateM 3 x
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0 ,1,2],[0,2,0],[0,2,1],[0,2,2],[1,0,0],[1,0,1],[1,0 ,2],[1,1,0],[1,1,1],[1,1,2],[1,2,0],[1,2,1],[1,2,2 ],[2,0,0],[2,0,1],[2,0,2],[2,1,0],[2,1,1],[2,1,2], [2,2,0],[2,2,1],[2,2,2]]
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
解决方案 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
Prelude> let x = [0..2]
Prelude> import Control.Applicative
Prelude Control.Applicative> (,,) <$> x <*> x <*> x
[(0,0,0),(0,0,1),(0,0,2),(0,1,0),(0,1,1),(0,1,2),(0,2,0),(0,2,1),(0,2,2),(1,0,0),(1,0,1),(1,0,2),(1,1,0),(1,1,1),(1,1,2),(1,2,0),(1,2,1),(1,2,2),(2,0,0),(2,0,1),(2,0,2),(2,1,0),(2,1,1),(2,1,2),(2,2,0),(2,2,1),(2,2,2)]
If you want an [[a]]
instead, there is a very simple function for this:
Prelude> sequence (replicate 3 x)
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2],[0,2,0],[0,2,1],[0,2,2],[1,0,0],[1,0,1],[1,0,2],[1,1,0],[1,1,1],[1,1,2],[1,2,0],[1,2,1],[1,2,2],[2,0,0],[2,0,1],[2,0,2],[2,1,0],[2,1,1],[2,1,2],[2,2,0],[2,2,1],[2,2,2]]
or (thanks sdcvvc)
Prelude> import Control.Monad
Prelude Control.Monad> replicateM 3 x
[[0,0,0],[0,0,1],[0,0,2],[0,1,0],[0,1,1],[0,1,2],[0,2,0],[0,2,1],[0,2,2],[1,0,0],[1,0,1],[1,0,2],[1,1,0],[1,1,1],[1,1,2],[1,2,0],[1,2,1],[1,2,2],[2,0,0],[2,0,1],[2,0,2],[2,1,0],[2,1,1],[2,1,2],[2,2,0],[2,2,1],[2,2,2]]
这篇关于Haskell泛化问题(涉及列表解析)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文