-1

One reason that pushes me away from functional languages like Lisp is that I have no idea how to do a 'raw' array iteration. Say, I have an array in C that represents the screen pixels's RGB values. Changing colors is trivial with a for loop in C, but how do you do this elegantly in Lisp?

EDIT:

Sorry, I haven't phrased my question correctly. In C, when I want to change color on the screen, I simply write a for loop over a part of the array. BUT in scheme, clojure or haskell all data is immutable. So when I change a part of matrix, it would return a brand new matrix. That's a bit awkward. Is there a 'clean' way to change the color of a part of matrix without recursing over whole array and making copies?

kuniqs
  • 308
  • 1
  • 9
  • 1
    What makes you think Lisp is a "functional language"? (c.f. http://stackoverflow.com/questions/6021649/is-it-true-that-lisp-is-not-a-functional-programming-language ) – Wooble May 21 '14 at 11:09
  • It's even trivialler in Lisp, since the loop design pattern can be abstracted out into suitable "map" procedures which do the looping for you. – molbdnilo May 21 '14 at 21:05

2 Answers2

1

In a functional language, you would use recursion. The recursion scheme can be named.

For example, to recurse over an array of data, applying a function to each pixel, you can manually recurse over the structure of the array:

map f []     = []             
      -- the empty array
map f (x:xs) = f x : map f xs  
      -- apply f to the head of the array, and loop on the tail.

(in Haskell).

This recursive form is so common it is called map in most libraries.

Don Stewart
  • 137,316
  • 36
  • 365
  • 468
0

To "iterate" through an array in some language like Lisp is a simple map. The structure is (map f x) where f is a function you want applied to every element of the list/array x.

ThreeFx
  • 7,250
  • 1
  • 27
  • 51