سؤال

for the pattern match in curry function, why does it try to match the later parameter instead of the first paramter. eg as below, it tried to match the second parameter and the result is "a", but why not "b" which match the first parameter?

   def curr3(n:String):String=>String={
     case "a"=>"a"
     case "b"=>"b"
   }
   println(curr3("b")("a"))
هل كانت مفيدة؟

المحلول

Let's step through your function:

1.We apply the first parameter "b" to curr3 and get back a function that takes a string and gives us back a string:

  val first:String => String = curr3("b")

which is equivalent to (basically we've thrown away the first parameter n):

  val first:String => String = {
    case "a" => "a"
    case "b" => "b"
  }

2.We apply the second parameter to first and get back "a":

  val second:String = first("a")
  println(second) // prints a

So the first parameter is taken in but never used. If you want to match on the first parameter you could do this:

  def curr3(n: String): String => String = s => n match {
    case "a" => "a"
    case "b" => "b"
  }

But now we're just throwing away the second parameter s. I think you don't really need a curried function here (unless you want to do something with the second paramater) and you could do something simple similar to the first example:

  def curr3(n: String) = n match {
    case "a" => "a"
    case "b" => "b"
  }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top