Categories
Technology

Now how do you do this in functional programming

Consider the following piece of code:

...
int flag=0;
for(int i=0;i<10;i++){
   if(val==arr[i]){
      flag=1;
      break;
   }
}
if(flag==1){
   System.out.println("Found.");
}
else{
   System.out.println("Not found.");
}
...

In functional programming, we cannot assign values to variables; variables can only be initialized. So I can't use a 'flag', the reason being that if I initialize the 'flag' outside the for, I can't change its value inside the for and if I initialize the 'flag' inside the for, I can't use it outside because of scoping.

For people new to functional programming, here's an excerpt from Wikipedia:

Functional programming languages have the following features (or should I call it restrictions?):

...Functional programming can be contrasted with imperative programming. Functional programming appears to be missing several constructs often (though incorrectly) considered essential to an imperative language such as C or Pascal. For example, in strict functional programming, there is no explicit memory allocation and no explicit variable assignment. However, these operations occur automatically when a function is invoked: memory allocation occurs to create space for the parameters and the return value, and assignment occurs to copy the parameters into this newly allocated space and to copy the return value back into the calling function. Both operations can only occur on function entry and exit, so side effects of function evaluation are eliminated.

I had such a requirement in my program. I was using XSLT to program something and I came across this requirement. (XSLT is also a functional programming language). I then used some XPath constructs to solve it but wondered if there is a standard way to solve it in functional programming languages.

I am new to functional programming (although I have been doing XSLT scripting for the last 1 year) and I am still looking for a standard solution to this pattern.