官术网_书友最值得收藏!

functions

Functions can be nested, as demonstrated in the following example:

function a(x) 
    z = x * 2 
    function b(z) 
        z += 1 
    end 
    b(z) 
end 
 
d = 5 
a(d) #=> 11 

A function can also be recursive, that is, it can call itself. To show some examples, we need to be able to test a condition in code. The simplest way to do this in Julia is to use the ternary operator ? of the form expr ? b : c (ternary because it takes three arguments). Julia also has a normal if construct. (Refer to the Conditional evaluation section of Chapter 4, Control Flow.) expr is a condition and, if it is true, then b is evaluated and the value is returned, else c is evaluated. This is used in the following recursive definition to calculate the sum of all the integers up to and including a certain number:

sum(n) =  n > 1 ? sum(n-1) + n : n 

The recursion ends because there is a base case: when n is 1, this value is returned. Here is the famous function to calculate the nth Fibonacci number that is defined as the sum of the two previous Fibonacci numbers:

fib(n) = n < 2 ? n : fib(n-1) + fib(n-2)

When using recursion, care should be taken to define a base case to stop the calculation. Also, although Julia can nest very deeply, watch out for stack overflows, because, until now, Julia has not done tail call optimization automatically.

主站蜘蛛池模板: 张家口市| 丰城市| 绵阳市| 桦甸市| 阿拉善盟| 当阳市| 莎车县| 万宁市| 清原| 南靖县| 奉化市| 从化市| 疏附县| 游戏| 平顶山市| 都江堰市| 尼玛县| 西华县| 怀宁县| 兰考县| 富裕县| 长治市| 利辛县| 万安县| 阳朔县| 邯郸市| 横山县| 武宁县| 余江县| 特克斯县| 贺州市| 镇安县| 扶绥县| 黑水县| 房产| 常宁市| 张家口市| 漠河县| 阿拉善右旗| 河津市| 洛阳市|