I couldn't find any documentation on this for Scala, but a lot for other programming languages which never or rarely use recursion.
The sequence should be allowed to be empty and contain doubles.
val nonEmpthySeq = Seq(1,2,3,4,4,4,5,6,7,7,67,8,9,9,10)
val oneElementSeq = Seq(4)
val empthySeq = Seq()
What I tried :
I can't write an answer to this, as my question is supposedly a duplicate.
Using pattern matching
def secondSmallest(xs: Seq[Int]): Option[Int] = xs match {
case Nil => None
case `xs` => Some(xs.distinct.sorted.apply(1))
}
super clean one-liner
def secondSmallest(xs: Seq[Int]): Option[Int] =
Try(xs.distinct.sorted.apply(1)).toOption
Both return
secondSmallest(nonEmpthySeq)
secondSmallest(oneElementSeq)
secondSmallest(empthySeq)
res0: Option[Int] = Some(2) res1: Option[Int] = None res2: Option[Int] = None
res1
explaination:
x::Nil
, for Seq(4)
in secondSmallest(oneElementSeq)
has to be None
as there is logically no second highest element in the list, so it has to be None
.
If you want the one element in case there is only one, you have to handle it with case x :: Nil => Some(x)
.
def secondSmallest(xs: Seq[Int]): Option[Int] = xs match {
case Nil => None
case x :: Nil => Some(x)
case `xs` => Some(xs.distinct.sorted.apply(1))
}