windows 10 pro office 2019 pro office 365 pro windows 10 home windows 10 enterprise office 2019 home and business office 2016 pro windows 10 education visio 2019 microsoft project 2019 microsoft project 2016 visio professional 2016 windows server 2012 windows server 2016 windows server 2019 Betriebssysteme office software windows server instagram takipçi instagram beğeni instagram görüntüleme instagram otomatik beğeni facebook beğeni facebook sayfa beğenisi facebook takipçi twitter takipçi twitter beğeni twitter retweet youtube izlenme youtube abone instagram

How to constrain types to specific types in scala

Asked By: Anonymous

I’d like to adapt this code as given here : Find min and max elements of array

def minMax(a: Array[Int]) : (Int, Int) = {
  if (a.isEmpty) throw new java.lang.UnsupportedOperationException("array is empty")
  a.foldLeft((a(0), a(0)))
  { case ((min, max), e) => (math.min(min, e), math.max(max, e))}

To work also with Long, Float and Double (since these are the types accepted by scala.math.min/max. I tried:

def getMinAndMax[@specialized(Int,Long,Float,Double) T](x: Seq[T]) : (T, T) = {
  if (x.isEmpty) throw new java.lang.UnsupportedOperationException("seq is empty")
  x.foldLeft((x.head, x.head))
  { case ((min, max), e) => (math.min(min, e), math.max(max, e))}

But this does not compile either. Any advice?


Answered By: Anonymous

You want a typeclass. Specifically, in this case, you want Ordering from the stdlib.

// It is more idiomatic to return an Option rather than throwing an exception,
// that way callers may decide how to handle that case.
def getMinAndMax[T : Ordering](data: IterableOnce[T]): Option[(T, T)] = {
  import Ordering.Implicits._ // Provides the comparison operators: < & >

  data.iterator.foldLeft(Option.empty[(T, T)]) {
    case (None, t) =>
      Some((t, t))
    case (current @ Some((min, max)), t) =>
      if (t < min) Some((t, max))
      else if (t > max) Some((min, t))
      else current

You can see the code running here.

techinplanet staff

Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno