MBD
MBD

Reputation: 95

scala: find the amount of a specific element in a list

I want to write a function count: (List[Int]) => Int in scala which counts the amount of a specific element in a list. I want to implement it this way:

count(2, List(2, 4, 5, 2, 2, 7)) 

should return 3. How can I do this in scala?

Upvotes: 0

Views: 74

Answers (1)

airudah
airudah

Reputation: 1179

List has an inbuilt count already like @Jeffery mentioned.

You asked to make it a function, so:

scala> val count = (x: Int, ls: List[Int]) => ls.count(_ == x)
count: (Int, List[Int]) => Int = <function2>

scala> count(2, List(2,4,5,2,2,7))
res1: Int = 3    

Upvotes: 2

Related Questions