0

I have just started to learn Scala after some experience with functional programming in other languages.

def freq(c:Char, y:String, list:List[(Char,Int)]): List[(Char,Int)] = list match{
  case _ =>  freq(c, y.filter(_ == c), list :: List((count(c,y),c))) 
  case nil => list
} 

In the above code I am getting an error when trying to concatenate the list recursively. The error is occurring in list::List((count(c,y),c)). The count method takes a char and a string and returns an int based on how many times that char occurs.

Any help would be much appreciated. The error I am getting states found [(Char,Int)] required (Char,Int).

0

2 Answers 2

2

Cons operator (::) is an infix operator so if you want to get a type of List[T] and not List[List[T]] then you should write

freq(c, y.filter(_ == c),(count(c,y),c)) :: list)
Sign up to request clarification or add additional context in comments.

5 Comments

Found (Char,Int) required List[(Char,Int)]??
In which line? BTW: c is of type Char and a tuple you're creating should have second element of type Int - it still will not compile.
The return type of count is an Int while c is a char.
So you should write: freq(c, y.filter(_ == c),(c, count(c,y))) :: list)
Like this case _ => freq(c, y.filter(_ == c),(c, count(c,y)) :: list) it compiles :P
0

Also you need to switch the 2 match cases because nil would never be evaluated this way. _ will catch nil too and never continue to reach the second case.

1 Comment

Thanks I will keep that in mind, it works a little different from Haskell where I can just put [] = [] or otherwise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.