reversing the elements of list

178 views
Skip to first unread message

Harit Himanshu

unread,
Jun 7, 2015, 4:46:58 PM6/7/15
to scala...@googlegroups.com
This is again in spirit of learning Scala and solving S99 problems.

The problem statement looks like  
P05 (*) Reverse a list.
Example:
scala> reverse(List(1, 1, 2, 3, 5, 8))
res0: List[Int] = List(8, 5, 3, 2, 1, 1)

and my solution looks like  

scala> def reverse[T](l:List[T], reversed:List[T]): Option[List[T]] = {
     |     l match {
     |       case Nil => if (reversed.nonEmpty) Some(reversed) else None
     |       case head::tail => reverse(tail, head::reversed)
     |     }
     |   }
reverse: [T](l: List[T], reversed: List[T])Option[List[T]]

scala> reverse(List(1,2,3), Nil)
res0: Option[List[Int]] = Some(List(3, 2, 1))

scala> reverse(List(), Nil)
res1: Option[List[Nothing]] = None

scala> reverse(List("one", "two", "three"), Nil)
res2: Option[List[String]] = Some(List(three, two, one))

scala> 

Questions
As you could see I have made use of two things, learned from my last post about "find nth element from list". My specific question is  
  1. Is it a good idea to use Option most of the places where we see returning Null/None is possible?
Thanks

Som Snytt

unread,
Jun 7, 2015, 6:54:52 PM6/7/15
to Harit Himanshu, scala-user
The empty list reversed is still the empty list. Also, null is not possible; it's your job to ensure that.

scala> Nil.reverse
res2: List[Nothing] = List()


--
You received this message because you are subscribed to the Google Groups "scala-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-user+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Harit Himanshu

unread,
Jun 8, 2015, 12:56:59 AM6/8/15
to Som Snytt, scala-user
Got that Som. Thanks
Reply all
Reply to author
Forward
0 new messages