英文:
Iterating over mappings of a function in Haskell
问题
现在,我需要遍历所有的映射 (Coord, Color)
。我该如何实现这个?
英文:
Suppose
data Color = Color Int Int Int -- RGB, each R, G and B in [0..255]
deriving (Show,Eq)
data Coord = Coord Int Int -- x- and y-coordinates of a pixel
data Picture = Picture (Coord -> Color) -- A Picture is just a function mapping a coordinate to its respective pixel color.
Now, I need to iterate over all mappings (Coord, Color)
. How can I accomplish that?
答案1
得分: 4
如果您想知道如何将您的Coord -> Color
函数转换为列表形式的具体映射[(Coord, Color)]
,那么您需要知道通常情况下这实际上并不可能,或者至少不实际。
其中一件事是添加两个参数,表示图片的高度和宽度:
data Picture = Picture Int Int (Coord -> Color)
然后,您可以将其转换为[(Coord, Color)]
映射:
getMapping :: Picture -> [(Coord, Color)]
getMapping (Picture width height f) =
[(Coord x y, f (Coord x y)) | x <- [0..width-1], y <- [0..height-1]]
英文:
If you want to know how to convert your Coord -> Color
function into a concrete mapping in the form of a list [(Coord, Color)]
then you need to know that in general this is not really possible or at least not practical.
One thing you can do is add two parameters denoting the height and the width of the picture:
data Picture = Picture Int Int (Coord -> Color)
Then you can convert it into a [(Coord, Color)]
mapping:
getMapping :: Picture -> [(Coord, Color)]
getMapping (Picture width height f) =
[(Coord x y, f (Coord x y)) | x <- [0..width-1], y <- [0..height-1]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论