Scala Filter Patterns from String
I have the following code that is supposed to count the number of times a character appears in a string.
def filter[T] (l: List[T], stays: T ⇒ Boolean): List[T] = {
if( l == Nil ) return Nil
if (stays(l.head) == true) l.head :: filter(l.tail, stays)
else filter(l.tail, stays)
}
def countChar(s: String): List[(Char, Int)] = {
if (s == "") Nil
else (s(0), s.count(_ == s(0))) :: countChar(filter(s.toList, _ == s(0)).mkString)
}
Now my problem is that in
filter(s.toList, _ == s(0))
I am getting error: Missing parameter type. I understand it comes from function nesting?
How can I fix this? I know String has some ways to do what I want, but I would like to use my own filtering method.
source to share
This is a limitation of the Scala compiler: it tries to figure out what type T
in filter
should be using both arguments l
and stays
. But it fails because the argument type is stays
not specified.
If you don't want to specify the type of the argument stays
every time (i.e. filter(s.toList, (_: Char) == s(0)
), you can split the argument list filter
in two:
def filter[T] (l: List[T])(stays: T ⇒ Boolean): List[T]
Then Scala will know what T
is there Char
by the time the type is parsed stays
. You can call this one filter
with filter(l.tail)(stays)
.
source to share