Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter in functional languages with original non-filtered elements?

I want to return an array that that maps some filtered elements - but I want to keep the non-filtered elements where they are. i.e. Is there an easy way to do this?:

array
.filter(
  function(element){
    // some test
  }
)
.map(
  function(element){
    // some mapping
  }
)

The closest solution I've come up with is something along the lines of:

array
.map(
  function(value, index){
    if (<test>) {
      return <mapping>(value);
    }
  }
)

but I feel this somewhat breaks the spirit of functional programming.

I'm not asking for a specific language implementation, although an example in Scala or JavaScript would be nice.

EDIT: Here's a concrete example of what I'm looking for:

[1,2,3,4,11,12]

Mapping all elements to element*10, for all elements in array which are greater than 10, should yield

[1,2,3,4,110,120]

EDIT2: I apologize for using the word "mutate." I did not mean mutate the original array - I was thinking more along the lines of mutating a copy of the array.

like image 486
Kevin Li Avatar asked Dec 21 '22 08:12

Kevin Li


1 Answers

It's not really going to be functional if you're using a mutable collection. But you can use transform in Scala:

scala> val a = Array(1,2,3,4,11,12)
a: Array[Int] = Array(1, 2, 3, 4, 11, 12)

scala> a.transform {i => if(i > 10) i * 10 else i}
res10: scala.collection.mutable.WrappedArray[Int] = WrappedArray(1, 2, 3, 4, 110, 120)

edit: If you want filter and map separated, use a view:

scala> a
res22: Array[Int] = Array(1, 2, 3, 4, 11, 12)

scala> a.view.filter(_ > 10).transform(_ * 10)
res23: scala.collection.mutable.IndexedSeqView[Int,Array[Int]] = SeqViewF(...)

scala> a
res24: Array[Int] = Array(1, 2, 3, 4, 110, 120)
like image 143
Luigi Plinge Avatar answered Dec 24 '22 00:12

Luigi Plinge