Which function has the same behaviour as collect but keep the elements that do not satisfy the predicate - scala

I am looking for a function that looks like collect. This function must keep the element that do not satisfy the predicate.
This behaviour be could expressed using map. Example :
# (0 to 10).map{
case e if e > 5 => e * e
case e => e // I want to keep elements to does not satisfy the predicate !
}
res3: collection.immutable.IndexedSeq[Int] = Vector(0, 1, 2, 3, 4, 5, 36, 49, 64, 81, 100)
I would like to be able to write this function like this :
# (0 to 10).map{
case e if e > 5 => e * e
}
scala.MatchError: 0 (of class java.lang.Integer)
$sess.cmd4$$anonfun$1.apply$mcII$sp(cmd4.sc:1)
$sess.cmd4$$anonfun$1.apply(cmd4.sc:1)
$sess.cmd4$$anonfun$1.apply(cmd4.sc:1)
scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:234)
scala.collection.immutable.Range.foreach(Range.scala:160)
scala.collection.TraversableLike$class.map(TraversableLike.scala:234)
scala.collection.AbstractTraversable.map(Traversable.scala:104)
$sess.cmd4$.<init>(cmd4.sc:1)
$sess.cmd4$.<clinit>(cmd4.sc:-1)
Unfortunately, I have not found a function that takes a PartialFunction to avoid MatchErrors.
Do you know a function with such a behaviour ?

I don't think there is a pre-defined method that does what you want, but you can use a PartialFunction's .applyOrElse to do it:
scala> implicit class MySeq[A](r: Seq[A]) {
def mapIfDefined(f: PartialFunction[A, A]): Seq[A] = {
r.map(f.applyOrElse[A, A](_, identity))
}
}
scala> (0 to 10).mapIfDefined{
case e if e > 5 => e * e
}
res1: Seq[Int] = Vector(0, 1, 2, 3, 4, 5, 36, 49, 64, 81, 100)

Unless I'm mistaken, collect does exactly what you're asking:
scala> List(1,2,3,4,5,6,7,8,9,10).collect {
| case e if e > 5 => e * e
| case e => e
| }
res0: List[Int] = List(1, 2, 3, 4, 5, 36, 49, 64, 81, 100)

Related

Generate sequence with unknown bound, based on condition

I want to generate sequance of all fibonacci numbers, that less then 10000
For example, this will generate 40 fibonacci numbers. But i want to stop generate them with some condition. How can i do this?
def main(args: Array[String]) {
val fibonacciSequence = for(i <- 1 to 40) yield fibonacci(i)
println(fibonacciSequence)
}
def fibonacci(i: Int) : Int = i match {
case 0 => 0
case 1 => 1
case _ => fibonacci(i - 1) + fibonacci(i - 2);
}
I want something like this: for(i <- 1 to ?; stop if fibonacci(i) > 100000)
This method, involving lazy infinite collection calculation, could produce suitable result:
import scala.Numeric.Implicits._
def fibonacci[N: Numeric](a: N, b: N): Stream[N] = a #:: fibonacci(b, a + b)
so
fibonacci(0L,1L).takeWhile(_ < 1000L).toList
yields
List(0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987)
If you don't want to use intermediate value to cache collection of proper type and init, you could just declare a val like this:
val fib: Stream[Long] = 0 #:: 1 #:: (fib zip fib.tail map { case (a, b) => a + b })
Using iterators and memoization (computing the current result based in the latest ones, not recomputing what has already been done), (method from Rosetta, similar to Odomontois's streams),
def fib() = Iterator.iterate((0,1)){ case (a,b) => (b,a+b)}.map(_._1)
To get the first nth values consider for instance,
def nfib(n: Int) = fib().zipWithIndex.takeWhile(_._2 < n).map(_._1).toArray
To get consecutive values up to a given condition or predicate,
def pfib(p: Int => Boolean) = fib().takeWhile(p).toArray
Thus, for example
nfib(10)
Array(0, 1, 1, 2, 3, 5, 8, 13, 21, 34)
pfib( _ < 55)
Array(0, 1, 1, 2, 3, 5, 8, 13, 21, 34)

How to replace values in one Seq with values from another Seq in Scala?

I have sequences:
val A = Seq(1,3,0,4,2,0,7,0,6)
val B = Seq(8,9,10)
I need a new sequence where 0 are replaced with values from second sequence:
Seq(1,3,8,4,2,9,7,10,6)
How to do that in functional style?
You can use map here, by replacing all 0s with the next element of b (by converting b to an iterator, and using next):
val a = Seq(1,3,0,4,2,0,7,0,6)
val b = Seq(8,9,10).iterator
a.map { e => if (e == 0) b.next else e } //Seq(1,3,8,4,2,9,7,10,6)
Not sure that iterators are really functional. Anyway, here's an alternative
val A = Seq(1,3,0,4,2,0,7,0,6)
val B = Seq(8,9,10)
A.foldLeft((B, Seq[Int]())) {case ((b, r), e) =>
if (e == 0 && ! b.isEmpty) (b.tail, b.head +: r) else (b, e +: r) }
._2.reverse
//> res0: Seq[Int] = List(1, 3, 8, 4, 2, 9, 7, 10, 6)
EDIT: Updated per the comment to leave the zeros if we're out of elements of B
EDIT2:
A pattern-matching variant is neater:
A.foldLeft((B, Seq[Int]())){case ((h +: t, r), 0) => (t, h +: r)
case ((b, r), e) => (b, e +: r)}
._2.reverse
And, based on what is proper monad or sequence comprehension to both map and carry state across?
A.mapAccumLeft(B, { case ((h +: t), 0) => (t, h)
case (b, e) => (b, e) }
(probably, I don't have scalaz installed to test it)
If you want to look at Tail Recursion then this suits you.
#annotation.tailrec
def f(l1: Seq[Int], l2: Seq[Int], res: Seq[Int] = Nil): Seq[Int] = {
if (l1 == Nil) res
else {
if (l1.head == 0 && l2 != Nil) f(l1.tail, l2.tail, res :+ l2.head)
else
f(l1.tail, l2, res :+ l1.head)
}
}
val A = Seq(1, 3, 0, 4, 2, 0, 7, 0, 6)
val B = Seq(8, 9, 10)
scala> f(A,B)
res0: Seq[Int] = List(1, 3, 8, 4, 2, 9, 7, 10, 6)
if you run out of elements in B then ,
val A = Seq(1, 3, 0, 4, 2, 0, 7, 0, 6)
val B = Seq(8, 9)
scala> f(A,B)
res1: Seq[Int] = List(1, 3, 8, 4, 2, 9, 7, 0, 6)
if elements in A are less than B then,
val A = Seq(1, 0)
val B = Seq(8, 9, 10)
scala> f(A,B)
res2: Seq[Int] = List(1, 8)

Merging streams in scala

I need help with merging two streams into one. The output has to be as follows:
(elem1list1#elem1list2, elem2list1#elem2list2...)
and the function breaks if any of streams is empty
def mergeStream(a: Stream[A], b: Stream[A]):Stream[A] =
if (a.isEmpty || b.isEmpty) Nil
else (a,b) match {
case(x#::xs, y#::ys) => x#::y
}
Any clue how to fix it?
You can also zip two Streams together, which will truncate the longer Stream, and flatMap them out of the tuples:
a.zip(b).flatMap { case (a, b) => Stream(a, b) }
Though I cannot speak to it's efficiency.
scala> val a = Stream(1,2,3,4)
a: scala.collection.immutable.Stream[Int] = Stream(1, ?)
scala> val b = Stream.from(3)
b: scala.collection.immutable.Stream[Int] = Stream(3, ?)
scala> val c = a.zip(b).flatMap { case (a, b) => Stream(a, b) }.take(10).toList
c: List[Int] = List(1, 3, 2, 4, 3, 5, 4, 6)
def mergeStream(s1: Stream[Int], s2: Stream[Int]): Stream[Int] = (s1, s2) match {
case (x#::xs, y#::ys) => x #:: y #:: mergeStream(xs, ys)
case _ => Stream.empty
}
scala> mergeStream(Stream.from(1), Stream.from(100)).take(10).toList
res0: List[Int] = List(1, 100, 2, 101, 3, 102, 4, 103, 5, 104)
You can use interleave from scalaz:
scala> (Stream(1,2) interleave Stream.from(10)).take(10).force
res1: scala.collection.immutable.Stream[Int] = Stream(1, 10, 2, 11, 12, 13, 14, 15, 16, 17)

Get list of primes to N

I'm trying to write a function which takes an Int and returns all of the prime numbers up to and including that Int.
for example "list of primes for 8" = List(3,5,7)
This is what I have so far :
def isPrime(i: Int): Boolean = {
if (i <= 1)
false
else if (i == 2)
true
else
!(2 to (i - 1)).exists(x => i % x == 0)
} //> isPrime: (i: Int)Boolean
def getListOfPrimesToN(n : Int) = {
}
for the function getListOfPrimesToN I plan to
1. create a List "l" of size n and populate it with elements ranging from 0 to n.
2. call map function of "l" and call isPrime for each element in List.
How to create the List of element 1 to N ?
Any alternative solutions for returning all of the prime numbers up to and including an Int N welcome.
You can solve this with infinite streams. If you had a stream primes of all the primes, you could just say primes.takeWhile(_ <= n) to get the primes up to and including n.
To get all the primes, you start with a stream of all the numbers starting from 2, the first prime. You can then skip all the even numbers since those are definitely not prime. Then you can skip all the other numbers that are not prime.
val primes = 2 #:: Stream.from(3,2).filter(isPrime)
Now you just need isPrime to check if a given number is prime. A number is prime if it is not divisible by any smaller prime. We actually need only consider primes whose square is not greater than the number (since, logically, a composite number's smallest prime factor can't be larger than its square root).
def isPrime(n: Int): Boolean =
primes.takeWhile(p => p*p <= n).forall(n % _ != 0)
Check this in the REPL:
scala> primes.takeWhile(_ <= 8).toList
res0: List[Int] = List(2, 3, 5, 7)
Caveat: This only works for positive numbers smaller than Integer.MAX_VALUE.
An implementation of the Sieve of Eratosthenes algorithm for efficiently finding prime numbers up to a given value N includes the following, (fixed and improved on this SO answer),
implicit class Sieve(val N: Int) extends AnyVal {
def primesUpTo() = {
val isPrime = collection.mutable.BitSet(2 to N: _*) -- (4 to N by 2)
for (p <- 2 +: (3 to Math.sqrt(N).toInt by 2) if isPrime(p)) {
isPrime --= p*p to N by p
}
isPrime.toImmutable
}
}
Hence
10.primesUpTo.toList
res: List(2, 3, 5, 7)
11.primesUpTo.toList
res: List(2, 3, 5, 7, 11)
Note Find prime numbers using Scala. Help me to improve for additional ideas and discussion.
Here is the code based on your:
scala> def isPrime(n: Int): Boolean =
| n >= 2 && (2 to math.sqrt(n).toInt).forall(n%_ != 0)
isPrime: (n: Int)Boolean
scala> def getListOfPrimesToN(n: Int): List[Int] =
| List.range(2, n+1) filter isPrime
getListOfPrimesTON: (n: Int)List[Int]
scala> getListOfPrimesToN(97)
res0: List[Int] = List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
Here is another solution using Stream:
scala> def getListOfPrimesToN(n: Int): List[Int] = {
| lazy val ps: Stream[Int] = 2 #:: Stream.from(3)
.filter(x => ps.takeWhile(p => p*p <= x).forall(x%_ != 0))
| ps.takeWhile(_ <= n).toList
| }
getListOfPrimesToN: (n: Int)List[Int]
scala> getListOfPrimesToN(97)
res0: List[Int] = List(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
How about this.
def getPrimeUnder(n: Int) = {
require(n >= 2)
val ol = 3 to n by 2 toList // oddList
def pn(ol: List[Int], pl: List[Int]): List[Int] = ol match {
case Nil => pl
case _ if pl.exists(ol.head % _ == 0) => pn(ol.tail, pl)
case _ => pn(ol.tail, ol.head :: pl)
}
pn(ol, List(2)).reverse
}

How can i interleave elements of 2 lists in scala

I'd like to combine two Lists of arbitrary length in such a way that elements from the 2nd List are inserted after every n-th element into the 1st List. If the 1st List length is less than n, no insertion results.
So having
val a = List(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
val b = List(101,102,103)
val n = 3
I want the resulting List to look like this:
List(1,2,3,101,4,5,6,102,7,8,9,103,10,11,12,13,14,15)
I have this working using a foldLeft on a, but I'm wondering how the same logic could be accomplished using Scalaz?
Thanks for everyone's answers. They were all helpful to me !
Meet my apomorphism friend
def apo[A, B](v: B)(f: B => Option[(A, Either[B, List[A]])]): List[A] = f(v) match {
case None => Nil
case Some((a, Left(b))) => a :: apo(b)(f)
case Some((a, Right(as))) => a :: as
}
Your interleave method can be implemented like this
def interleave[A](period: Int, substitutes: List[A], elems: List[A]): List[A] =
apo((period, substitutes, elems)){
case (_, _, Nil) => None
case (_, Nil, v :: vs) => Some((v, Right(vs)))
case (0, x :: xs, vs) => Some((x, Left((period, xs, vs))))
case (n, xs, v :: vs) => Some((v, Left((n - 1, xs, vs))))
}
This gives:
scala> interleave(3, b, a)
res1: List[Int] = List(1, 2, 3, 101, 4, 5, 6, 102, 7, 8, 9, 103 , 10, 11 , 12, 13, 14, 15)
The good point is the computation ends when a or b are Nil unlike foldLeft. The bad news is interleave is no more tail recursive
This gets very simple with zipAll. Moreover, you are able to choose the amount of elements of the second array (in this case 1):
val middle = b.grouped(1).toList
val res = a.grouped(n).toList.zipAll(middle, Nil, Nil)
res.filterNot(_._1.isEmpty).flatMap(x => x._1 ++ x._2)
Or if you prefer, one-liner:
a.grouped(n).toList.zipAll(b.map(List(_)), Nil, Nil).filterNot(_._1.isEmpty).flatMap(x => x._1 ++ x._2)
You can also make an implicit class, so you could call a.interleave(b, 3) or with an optional thrid parameter a.interleave(b, 3, 1).
How about this:
def process[A](xs: List[A], ys: List[A], n: Int): List[A] =
if(xs.size <= n || ys.size == 0) xs
else xs.take(n):::ys.head::process(xs.drop(n),ys.tail,n)
scala> process(a,b,n)
res8: List[Int] = List(1, 2, 3, 101, 4, 5, 6, 102, 7, 8, 9, 103, 10, 11, 12, 13, 14, 15)
scala> val a = List(1,2,3,4,5,6,7,8,9,10,11)
a: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)
scala> process(a,b,n)
res9: List[Int] = List(1, 2, 3, 101, 4, 5, 6, 102, 7, 8, 9, 103, 10, 11)
scala> val a = List(1,2,3,4,5,6,7,8,9)
a: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> process(a,b,n)
res10: List[Int] = List(1, 2, 3, 101, 4, 5, 6, 102, 7, 8, 9)
scala> val a = List(1,2,3,4,5,6,7,8)
a: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)
scala> process(a,b,n)
res11: List[Int] = List(1, 2, 3, 101, 4, 5, 6, 102, 7, 8)
Your request is "If the 1st List length is less than n, no insertion results", then my code should change to:
def process[A](xs: List[A], ys: List[A], n: Int): List[A] =
if(xs.size < n || ys.size == 0) xs
else xs.take(n):::ys.head::process(xs.drop(n),ys.tail,n)
What about:
def interleave[A](xs: Seq[A], ys: Seq[A], n: Int): Seq[A] = {
val iter = xs grouped n
val coll = iter zip ys.iterator flatMap { case (xs, y) => if (xs.size == n) xs :+ y else xs }
(coll ++ iter.flatten).toIndexedSeq
}
scala> interleave(a, b, n)
res34: Seq[Int] = Vector(1, 2, 3, 101, 4, 5, 6, 102, 7, 8, 9, 103, 10, 11, 12, 13, 14, 15)
scala> interleave(1 to 2, b, n)
res35: Seq[Int] = Vector(1, 2)
scala> interleave(1 to 6, b, n)
res36: Seq[Int] = Vector(1, 2, 3, 101, 4, 5, 6, 102)
scala> interleave(1 to 7 b, n)
res37: Seq[Int] = Vector(1, 2, 3, 101, 4, 5, 6, 102, 7)
scala> interleave(1 to 7, Nil, n)
res38: Seq[Int] = Vector(1, 2, 3, 4, 5, 6, 7)
scala> interleave(1 to 7, Nil, -3)
java.lang.IllegalArgumentException: requirement failed: size=-3 and step=-3, but both must be positive
It is short, but it is not the most efficient solution. If you call it with Lists for example, the append-operations (:+ and ++) are expensive (O(n)).
EDIT: I'm sorry. I notice now, that you want to have a solution with Scalaz. Nevertheless the answer may be useful therefore I won't delete it.
Without Scalaz and recursion.
scala> a.grouped(n).zip(b.iterator.map{ Some(_) } ++ Iterator.continually(None)).flatMap{ case (as, e) => if (as.size == n) as ++ e else as }.toList
res17: List[Int] = List(1, 2, 3, 101, 4, 5, 6, 102, 7, 8, 9, 103, 10, 11, 12, 13, 14, 15)
Generic way:
def filled[T, A, That](a: A, b: Seq[T], n: Int)(implicit bf: CanBuildFrom[A, T, That], a2seq: A => Seq[T]): That = {
val builder = bf()
builder.sizeHint(a, a.length / n)
builder ++= a.grouped(n).zip(b.iterator.map{ Some(_) } ++ Iterator.continually(None)).flatMap{ case (as, e) => if(as.size == n ) as ++ e else as }
builder.result()
}
Usage:
scala> filled("abcdefghijklmnopqrstuvwxyz", "1234", 3)
res0: String = abc1def2ghi3jkl4mnopqrstuvwxyz
scala> filled(1 to 15, 101 to 103, 3)
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 101, 4, 5, 6, 102, 7, 8, 9, 103, 10, 11, 12, 13, 14, 15)
scala> filled(1 to 3, 101 to 103, 3)
res70: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 101)
scala> filled(1 to 2, 101 to 103, 3)
res71: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2)
here's the one you want:
import scala.annotation.tailrec
#tailrec
final def interleave[A](base: Vector[A], a: List[A], b: List[A]): Vector[A] = a match {
case elt :: aTail => interleave(base :+ elt, b, aTail)
case _ => base ++ b
}
...
interleave(Vector.empty, a, b)