0

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?

2 Answers 2

0

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"))
Sign up to request clarification or add additional context in comments.

Comments

0

You just need an underscore:

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

Comments

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.