- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 271字
- 2021-07-02 23:54:32
Pure functions
Pure functions are functions that do not possess any side effects; in other words, they do not change or alter any data or state outside of themselves. Additionally, they do not access any data or state except their provided parameters. Pure functions are like mathematical functions that are pure by nature.
Pure functions return a value that is only determined by its parameter values. Pure functions are easy to test as they rely only on their parameters and do not change or access any data or state outside of themselves. Pure functions are suitable for concurrency as they do not access and change global data or states.
The following list presents examples of pure and not pure functions:
- Printing a String literal to a console is not pure as it modifies an external state.
- Reading a file is not pure as it depends on the external state at different times.
- The length of a String is pure as it does not rely on a state. It only takes a String as input and returns the length as output.
- Getting the current date is not pure as it returns different values when called on different dates.
- Getting a random number is not pure as it returns different values each time it is called.
Using pure functions may sound very restrictive and impossible to utilize in real-world scenarios. For instance, file and database development in Swift cannot be perfectly pure but there are lots of other functionalities that can be developed using pure functions. We will see the benefits of pure functions in more detail and examples in upcoming chapters.
- 云計算環(huán)境下的信息資源集成與服務(wù)
- Effective Amazon Machine Learning
- Lean Mobile App Development
- 3D計算機視覺:原理、算法及應(yīng)用
- Hadoop大數(shù)據(jù)實戰(zhàn)權(quán)威指南(第2版)
- 達夢數(shù)據(jù)庫性能優(yōu)化
- SQL應(yīng)用及誤區(qū)分析
- 編寫有效用例
- Splunk智能運維實戰(zhàn)
- 計算機組裝與維護(微課版)
- 二進制分析實戰(zhàn)
- 爬蟲實戰(zhàn):從數(shù)據(jù)到產(chǎn)品
- 中文版Access 2007實例與操作
- Expert Python Programming(Third Edition)
- 利用Python進行數(shù)據(jù)分析(原書第2版)