Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return all positives and the first negative number in a list using functional programming?

Imagine I have an unsorted list of positive & negative ints. I want to return a list containing all the positive ints, and the first negative number, but then ignore all subsequent negative numbers from the list, while preserving the ordering.

Imperatively I could do:

l = [1, 2, -4, 5, -6, -1, 3]
out = []
first = true
for n in l:
    if n >= 0:
        out.push(n)
    else if first:
        out.push(n)
        first = false

// out = [1, 2, -4, 5, 3]

How could I do this with FP in Scala? I was thinking (probably won't compile...):

val l = List(1, 2, -4, 5, -6, -1, 3)
val posl = l.map(_ >= 0)
val negl = l.zipWithIndex.map((n, i) => if (n < 0) (i, n) else (None, None)).head
// now split posl at negl._1, and create a new list of leftSlice :: negl._2 :: rightSlice?

Is this the right approach, or is there a more elegant, succinct way?

like image 450
jbrown Avatar asked Dec 27 '14 15:12

jbrown


People also ask

How do you print positive and negative numbers in Python?

Python Code:n = float(input("Input a number: ")) if n >= 0: if n == 0: print("It is Zero! ") else: print("Number is Positive number. ") else: print("Number is Negative number. ")

How do you store negative values in an array?

Method 1 (Simple : O(n2)): The idea is to use two nested loop. For each element arr[i], find negative of arr[i] from index i + 1 to n – 1 and store it in another array. For output, print negative positive value of the stored element.

How do you find the positive number in a list Python?

Using the “lambda” function: As we know, the lambda function applies the condition in each element. So, Using lambda we can check whether the number is greater than zero or not. If it is greater than zero, It will print the list of all positive numbers.


1 Answers

It wouldn't be a proper functional programming question without a slightly-too-clever recursion+pattern matching answer.

def firstNegAllPos(l:List[Int]):List[Int] = {
   l match{
      case x::xs if x>=0 => x::firstNegAllPos(xs)
      case x::xs if x<0 => x::xs.filter(_>=0)
      case Nil => Nil
   }
}
like image 93
Dave Griffith Avatar answered Oct 11 '22 13:10

Dave Griffith