Search code examples
scalacurryingpolymorphic-functions

Pass Search term and Operator to Scala Polymorphic Function


I have this polymorphic function:

def findFirst[A](as: Array[A], p: A => Boolean): Int = {
    @annotation.tailrec
    def loop(n: Int): Int = {
        if(n >= as.length) -1
        else if(p(as(n))) n
        else loop(n + 1)
    }
    loop(0)
}

From functional programming in Scala and I want to pass the operator < Is it equal to a specific value >. How Would I do this? I currently have this:

println(findFirst(Array("abc", "def", "ghi"), == "def"))

Here the operator is < == "def">. Scala doesn't like that but I can't seem to figure out a way to pass in that value, operator pair. Something tells me currying could be used here?


Solution

  • The full syntax to specify this function would be:

    (x: String) => x == "def"
    

    So you can do:

    println(findFirst(Array("abc", "def", "ghi"), (x: String) => x == "def"))
    

    However, if you change the findFirst definition to be two separate parameter lists:

    def findFirst[A](as: Array[A])(p: A => Boolean): Int = {
      ...
    }
    

    Then scala can look at the first parameter (the array), see that A must be String, and infer that the type of the second parameter must be String => Boolean, so you can omit the type annotation:

    println(findFirst(Array("abc", "def", "ghi"))(x => x == "def"))
    

    Or better yet:

    println(findFirst(Array("abc", "def", "ghi"))(_ == "def"))