- Julia 1.0 Programming Complete Reference Guide
- Ivo Balbaert Adrian Salceanu
- 254字
- 2021-06-24 14:21:45
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.
- 黑客攻防從入門到精通(實戰秘笈版)
- 流量的秘密:Google Analytics網站分析與優化技巧(第2版)
- Vue.js設計與實現
- 信息可視化的藝術:信息可視化在英國
- Instant Zepto.js
- Ext JS Data-driven Application Design
- Oracle 12c中文版數據庫管理、應用與開發實踐教程 (清華電腦學堂)
- 可解釋機器學習:模型、方法與實踐
- Angular開發入門與實戰
- Learning OpenStack Networking(Neutron)(Second Edition)
- 計算機應用基礎案例教程
- Python Deep Learning
- Hacking Android
- Docker:容器與容器云(第2版)
- Learning Image Processing with OpenCV