1

I am trying to set a default value (x) => x for the parameter keyFunction in the following function:

def count[A, B](list: List[A], keyFunction: (A) => B, isRatio : Boolean = false): Map[B, Double] = {
    lazy val number = list.size.toDouble
    list.groupBy(keyFunction).map{
      case (key, group) => if (isRatio) (key, group.size/number) else (key, group.size.toDouble)
    }
  }

I know a dumb solution is just to define another function:

  def simplyCount[A] (list: List[A], isRatio: Boolean = false): Map[A, Double] = count(list, (e: A) => e, isRatio)

How can I do it in a better way? Thanks in advance.

1 Answer 1

3

You can add the default argument as (x: A) => x, but you'll have to separate it into a separate parameter list if you want Scala to automatically infer the type only given the list:

def count[A, B](list: List[A])(keyFunction: (A) => B = (x: A) => x, isRatio: Boolean = false): Map[B, Double] {
  ???
}

count(List("a", "B", "a", "c"))()
// Map(a -> 2.0, c -> 1.0, B -> 1.0)

You can do it as one parameter list, but you'll have to explicitly give it the type since the type inference won't be able to figure it out:

def count[A, B](list: List[A], keyFunction: (A) => B = (x: A) => x, isRatio: Boolean = false): Map[B, Double] {
  ???
}

count[String,String](List("a", "B", "a", "c"))
// Map(a -> 2.0, c -> 1.0, B -> 1.0)
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, got it. It needs to be two separate parameter lists in order for the type inference to disambiguate what A means in A=>A just from the List[A]. Updated.
Excellent! Both exactly work. Thanks for your nice solutions and effort.

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.