跳到主要內容
← 回到學習

學習 · 面試考題

Functional Programming介紹

目錄 · 3 個段落
  1. 01Imperative(命令式) is How to do stuff
  2. 02Declarative(宣告式) is What's stuff
  3. 03複雜的時候 就有差別了~

命令式 (Imperative) v.s 宣告式 (Declarative)

  • 命令式 Imperative:強調的是執行過程,通常會暴露非常多細節,比較具象
  • 宣告式 Declarative:強調的是執行結果,在思考過程中會隱藏細節,比較抽象

Functional programming 是 Declarative Paradigm 的代表,邏輯為用較為抽象的程式碼,理解程式碼想要達到怎樣的目標,Function 之間不會互相共用 state 狀態,而 Imperative 代表 OOP 比較容易寫出狀態互相依賴的程式碼。

Imperative(命令式) is How to do stuff

Imperative programming is a programming paradigm that uses statements that change a program's state.

著重在 HOW,具體表達程式碼該做什麼才能達到目標,比較像我以前撰寫程式的思維,程式一步一步按著順序照著你給他指示執行。Imperative 比較常運用 Statement ,也就是 if , while , for , switch 等。

  • Example: OOP

  • Stateful

  • Can mutate state

  • 常會有 Side Effect 發生

Declarative(宣告式) is What's stuff

Declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow.

著重在該做什麼 WHAT ,並採取抽象化流程。Declarative 比較常運用表達式 expression,表達式特色是單純運算並一定會有返回值

  • Example: FP

  • Stateless: 你只要專心於當前算式,結束後再也不用管他

  • Constants, immutability

  • No Side Effect

// Imperative is How to do stuff
var array = [3,2,1]
var total = 0
for( var i = 0 ; i <= array.length ; i ++ ){
    total += array[i]
}
javascript
// Declarative is What's stuff
var array = [3,2,1]
array.reduce(function( previous, current ){ 
    return previous + current 
})
javascript

複雜的時候 就有差別了~

今天有一個函式 doStuff ,input 是一個字串 'Welcome to FP world ',需要

  • 轉小寫、去掉空格 welcome to fp world

  • 輸出個別字串長度 > 3 字元的字串 welcome world

  • 反轉 world welcome

// Imperative is How to do staff
// 'Welcome to FP world'
const doStuff = str => {
  const lower = str.toLowerCase()  // 'welcome to fp world'
  const words = lower.split(' ') // ['welcome', 'to', 'fp', 'world']
 
  words.reverse() // ['world', 'fp', 'to', 'welcome']
 
  for(let i in words) {
    words[i] = words[i].trim()
  } // ['world', 'fp', 'to', 'welcome']
 
  let keepers = []
 
  for(let i in words) {
    if(words[i].length > 3) {
      keepers.push(words[i])
    }  // ['world', 'welcome']
  }
 
  return keepers.join(' ') // 'world welcome'
}
 
doStuff('Welcome to FP world')
javascript
// Declarative is What's stuff
// 'Welcome to FP world'
const doStuff = _.compose(
  join(' '),
  _.filter(x => x.length > 3),
  reverse,
  _.map(trim),
  split(' '),
  toLowerCase
)
javascript
BASISFPOOP
DataUses immutable data.Uses mutable data.
ModelFollow a declarative programming model.Follow an imperative programming model.
ExecutionThe statements can be executed in any order.The statements should be executed in particular order.
IterationRecursion is used for iterative data.Loops are used for iterative data.
ElementThe basic elements are Variables and Functions.The basic elements are objects and methods.
UseOften be used when there are few things with more operations.Often be used when there are many things with few operations.

目錄