What is the name of feature that allows separate function implementations for different values of parameters?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-24 10:10:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!