Using partial functions in Scala - how does it work?

前端 未结 2 1382
梦谈多话
梦谈多话 2020-12-02 03:48

I\'m new to Scala, I\'m using 2.9.1, and I\'m trying to get my head around how to use partial functions. I have a basic understanding of curried functions, and I know that

2条回答
  •  抹茶落季
    2020-12-02 04:38

    Rex Kerr's explanation is very good -- and no surprise there either. The question is clearly mixing up partial functions with partially applied functions. For whatever it is worth, I made the same confusion myself when I learned Scala.

    However, since the question does draw attention to partial functions, I'd like to speak of them a bit.

    Many people say that partial functions are functions that are not defined for all input, and that's true of mathematics, but not of Scala. In Scala, a function may not be defined for all input either. In fact, since partial function inherit from function, then function includes all partial functions as well, making that inevitable.

    Others mention the method isDefinedAt, which is, indeed, a difference, but one mostly about implementation. That's so true that Scala 2.10 will probably be released with a "fast partial function", which does not rely on isDefinedAt.

    And a few people even imply that the apply method for partial functions do something different than the apply method for functions, like only executing for the input that is defined -- which could not be farther from the truth. The apply method is exactly the same.

    What partial functions really come down to is another method: orElse. That sums up all use cases for partial functions much better than isDefinedAt, because partial functions are really about doing one of the following things:

    • Chaining partial functions (which is what orElse does), so that an input will be tried on each partial function until one of them matches.
    • Doing something different if a partial function doesn't match, instead of throwing an exception, which is what would happen if you chain that different thing using orElse.

    I'm not saying everything can be easily implemented in terms of orElse, mind you. I'm just saying that partial functions are about doing something else when an input isn't defined for it.

提交回复
热议问题