Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Oz

Name: Anonymous 2011-10-12 14:21

In OZ there is a function called map, which allows you to manipulate each member of a list and create a new list.

Map [1 2 3 4 5] fun {$ X} [X+1] end

This will add one to each element of the list and create a new one. Which would leave me with

[2 3 4 5 6]


I am trying to do something where I compare each element of the list to a Key and then print it if it matches, else nil.

I can't figure a way to get the variable Key into the anonymous function, as it will just declare a new instance. Is there a way to do this easily? Or am I trying to do this the wrong way.

Name: Anonymous 2011-10-12 17:40

>>2
You do not want Key as an argument in the inner function:
fun {DoStuff List Key}
  {Map List
       fun {$ X} If X == Key then X else nil end end}
end


Variables from the containing scope are available to the nested function. This is called a closure, and it's a very handy concept that you ought to learn to wield.

It is very useful for higher order programming. E.g.:
fun {MakeAdder N}
  fun {$ M} N + M end
end

This will return a function that can be applied to another number to add N, e.g.
{Show {{MakeAdder 1} 2}}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List