Scala Implementation of the last haskell method

I am trying to make some sample programs in scala to get to know the language better. For this, I'm trying to reimplement some of the built-in methods in Haskell. Most of these methods, I am sure, are also implemented in scala too, but this is only for my practice. I think I can post some code snippets (not all of them) to get a better way to do something and confirm my understanding of scala. So please let me know if this is not the place for this.

Here is my scala implementation to get the last element of any list. This is the right way to do things. Using Anyam, am I losing the type of the object contained in the list? Is it implemented in scala?

  def getLast(xs: List[Any]): Any = xs match {
     case List()         => null
     case x :: List()    => x
     case _ :: ys        => getLast(ys) 
   }
+3
source share
2 answers

Parameterize the type of your function and use "Nil" instead of List () as follows:

  def getLast[T](xs: List[T]): T = xs match {
     case Nil         => null.asInstanceOf[T]
     case x :: Nil    => x
     case _ :: ys     => getLast(ys) 
   }

Also consider returning the Option type:

  def getLast[T](xs: List[T]): Option[T] = xs match {
     case Nil         => None
     case x :: Nil    => Some(x)
     case _ :: ys     => getLast(ys) 
   }

Using:

  val listOfInts = List(1,2,3)
  assert(getLast(listOfInts).isInstanceOf[Int])

  val listOfStrings = List("one","two","three")
  assert(getLast(listOfStrings).isInstanceOf[String])
+6
source

First, avoid null, and especially null.asInstanceOf[T]. Observe danger with primitives:

scala> null.asInstanceOf[Int]
res19: Int = 0

scala> null.asInstanceOf[Boolean]
res20: Boolean = false

Thus, the signature must be either List[T] => Tin which lastan exception is thrown on an empty iterator:

def last[T](ts: List[T]): T = ts match {       
    case Nil => throw new NoSuchElementException
    case t :: Nil => t                          
    case t :: ts => last(ts)                    
}   

Or instead: List[T] => Option[T]

def lastOption[T](ts: List[T]): Option[T] = ts match {
    case Nil => None                                   
    case t :: Nil => Some(t)                           
    case t :: ts => lastOption(ts)                     
}

def lastOption1[T](ts: List[T]): Option[T] = ts.reverse.headOption

def lastOptionInScala28[T](ts: List[T]): Option[T] = ts.lastOption  // :)
+5
source

Source: https://habr.com/ru/post/1732902/


All Articles