Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional equivalent to iterating over a 2D array

I have this function in Haskell (I am using the Haskell-SDL library):

pixel :: Surface -> Int16 -> Int16 -> Pixel -> IO Bool

pixel screen x y color

I want to use this to take a 2D array (or some other kind of data structure) and draw it to the screen, one pixel at a time. I looked into doing it with forM_ but can't figure out how to get it to operate on the x and y arguments.

I'm pretty new to Haskell and functional programming in general. I'm working my way through Yet Another Haskell Tutorial but this problem just has me stumped.

In case it's relevant to the solution, I'm trying to write a raytracer. It has to perform a calculation for each pixel, then write that pixel to the screen.

like image 590
n s Avatar asked Feb 11 '11 04:02

n s


1 Answers

If you are using nested lists, do:

import Control.Monad
plot :: Surface -> [[Pixel]] -> IO ()
plot surf = zipWithM_ (\ y -> zipWithM_ (\ x c -> pixel surf x y c) [0..]) [0..]
like image 53
Jeremiah Willcock Avatar answered Sep 20 '22 12:09

Jeremiah Willcock