Scala - increasing prefix of a sequence

后端 未结 4 679
离开以前
离开以前 2021-01-18 21:02

I was wondering what is the most elegant way of getting the increasing prefix of a given sequence. My idea is as follows, but it is not purely functional or any elegant:

4条回答
  •  不思量自难忘°
    2021-01-18 21:29

    I will interpret elegance as the solution that most closely resembles the way we humans think about the problem although an extremely efficient algorithm could also be a form of elegance.

    val sequence = List(1,2,3,2,3,45,5)
    val increasingPrefix = takeWhile(sequence, _ < _)
    

    I believe this code snippet captures the way most of us probably think about the solution to this problem.

    This of course requires defining takeWhile:

    /**
     * Takes elements from a sequence by applying a predicate over two elements at a time.
     * @param xs The list to take elements from
     * @param f The predicate that operates over two elements at a time
     * @return This function is guaranteed to return a sequence with at least one element as
     *         the first element is assumed to satisfy the predicate as there is no previous
     *         element to provide the predicate with.
     */
    def takeWhile[A](xs: Traversable[A], f: (Int, Int) => Boolean): Traversable[A] = {
      // function that operates over tuples and returns true when the predicate does not hold
      val not = f.tupled.andThen(!_)
      // Maybe one day our languages will be better than this... (dependant types anyone?)
      val twos = sequence.sliding(2).map{case List(one, two) => (one, two)}
      val indexOfBreak = twos.indexWhere(not)
      // Twos has one less element than xs, we need to compensate for that
      // An intuition is the fact that this function should always return the first element of
      // a non-empty list
      xs.take(i + 1)
    }
    

提交回复
热议问题