Functional Programming best practices

functional programming

I don't have a particular coding problem on hand this is just an excercise to improve my thought process.

Few months back I started learning about functional programming( mostly in R) and I fell in love with it.
Once in a while I try to think of problems that might be(correction: that I might find) difficult to solve in FP. Recently I thought of a situation where I might be more interested coding using imperative programming.

It seems to me that all higher order functions like map or reduce will iterate over whole list provided to them which makes sense.
How would you avoid iterating over whole list in functional programming for whatever reason – ex. list is too long, list is actually an infinite series, evaluating each item is very expensive etc.

So to make this problem more specific lets say I have an array and I want to return every member from zeroth member to first element whose value is greater than 10, but I want to stop searching through the list once I find that element greater than 10.

How would you solve this?

Example array: 1 2 3 1 2 3 11 1 2 3 1 2 3

I'm not looking for answer specifically in R I've seen enough Haskell & Scala to usually make sense of the code.

EDIT:

I forgot to mention why I would rather use imperative programing here.
I find that it is easier to stop iterating through array above with while/until loops because once I reach my terminating condition interpreter exits the loop, but map does not retain information about previous elements, and reduce solves that but I continues to iterate to the end of my list.

Best Answer

What you want to read more about is lazy evaluation. This basically means waiting until the last possible minute to do some work. So if you have the following Haskell code:

takeWhile (<= 10) $ map (+1) [1..]

[1..] is an infinite list, which you add 1 to every element, then take as many items in the list that are <= 10. However, the adding of one is done on demand, so you don't have to map the entire infinite list in order to get your result.

Haskell is lazy by default. In most all other languages, you have to explicitly request laziness. In Scala, that's done by using a lazy collection like a view, stream, or iterator. I don't know R.