I'm trying to group elements in a list, when I tried doing this with only one type, the first function works. But when I tried to use generics so I could group elements no matter the type, the function below doesn't do the work. Can you explain how can I do that?
def groupString (list: List[String]): List[List[String]] = {
def groupStringHelper(list: List[String], n: String, outputList:List[List[String]], outputListCurrent: List[String]):List[List[String]] =
if (list.isEmpty) outputList: outputListCurrent
else if (list.head == n) groupStringHelper(list.tail, n, outputList, outputListCurrent : list.head)
else groupStringHelper(list.tail, list.head, outputList : outputListCurrent, List(list.head))
groupStringHelper(list, null, List(), null).tail
}
def group [A](list: List[A]): List[List[A]] = {
def groupHelper(list: List[A], n: A, outputList:List[List[A]], currentList: List[A]):List[List[A]] =
if (list.isEmpty) outputList: outputListCurrent
else if (list.head == n) groupHelper(list.tail, n, outputList, currentList : list.head)
else groupHelper(list.tail, list.head, outputList : currentList, List(list.head))
groupHelper(list, null, List(), null).tail
}
CodePudding user response:
You would be wise to follow the advice (comment) from @Luis Miguel.
Here's a different approach you could take. (Scala 2.13.x)
def group[A](list: List[A]): List[List[A]] =
List.unfold(list){ lst =>
Option.when(lst.nonEmpty)(lst.span(_ == lst.head))
}
CodePudding user response:
The reason your code not compiled is not all type A
is nullable, e.g. Int.
So you can make your code work as:
def group [A >: Null](list: List[A]): List[List[A]] = {
def groupHelper(list: List[A], n: A, outputList:List[List[A]], currentList: List[A]):List[List[A]] =
if (list.isEmpty) outputList: currentList
else if (list.head == n) groupHelper(list.tail, n, outputList, currentList : list.head)
else groupHelper(list.tail, list.head, outputList : currentList, List(list.head))
groupHelper(list, null, List(), null).tail
}
However, the above code would not work for group[Int](List(1, 2, 3))
.
Here is a solution based on your code with removing null:
def group[A](list: List[A]): List[List[A]] = {
def groupHelper(list: List[A], n: A, outputList:List[List[A]], currentList: List[A]):List[List[A]] =
if (list.isEmpty) outputList: currentList
else if (list.head == n) groupHelper(list.tail, n, outputList, currentList : list.head)
else groupHelper(list.tail, list.head, outputList : currentList, List(list.head))
if(list.isEmpty) Nil else groupHelper(list.tail, list.head, Nil, list.take(1))
}