问题
In some programming languages one can specify the function implementation for particular values of arguments:
factorial[x] = x * factorial[x-1]
factorial[0] = 1
Calling the function with 0
will use the second definition while calling it with 3
will use the first definition.
I am aware that this is a kind of function overloading, but if I would search for languages with function overloading, I will find a lot that don't have this feature but only overload depending on arity or types. Is there a more specific name for this?
回答1:
Such case-by-case functions are known as piecewise functions in mathematics. For example, in Scala they can be implemented using case
statements like so
val factorial: Int => Int = {
case 0 => 1
case x => x * factorial(x - 1)
}
which outputs
factorial(4) // res1: Int = 24
This is a form of function definition using pattern matching.
Similarly, in Haskell we can define a function using pattern matching like so
factorial :: Integer -> Integer
factorial 0 = 1
factorial x = x * factorial (x - 1)
来源:https://stackoverflow.com/questions/57242614/what-is-the-name-of-feature-that-allows-separate-function-implementations-for-di