在Haskell中迭代函数的映射。

huangapple go评论48阅读模式
英文:

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]] 

huangapple
  • 本文由 发表于 2023年6月22日 19:59:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76531653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定