Tuesday, April 6, 2021

Clojure combinator

偶然看到一個 Eric Normand 的課程,它把 Clojure 的一些 high order functions 集中成一套課程,叫做 Clojure combinator 。哪些是 Clojure combinator 呢?有八個函數:

  • identity
  • constantly
  • complement
  • partial
  • fnil
  • comp
  • juxt
  • apply

妥善地運用這八個函數,可以讓語意更清晰。個人覺得 constantly 與 juxt 算是相對難學。
 
 constantly 是有一回,我要使用 alter-var-root 的時候,才發覺它的妙用。
 juxt 則是在三種情況下特別好用:
  1.  搭配使用 sort-by, group-by
  2.  修改既有的 hash map、生成新的 hash map --- 參考 lambdaisland 的 idiom 
  3.  取代 (comp vals select-keys) 
如果把上述的八個函數做個簡單的分類的話,我會分成四類:
1. 修改函數 (input arg 是函數, output 是 input arg 修改後得到的新函數) - fnil, complement, partial 
2. 組合函數 (input arg 含有超過一個函數, output 是將 input arg 重組而成的新函數) - comp, juxt 
3. 純生成函數 (input arg 可以不是函數,但 output 是一個新函數) - constantly
4. 非生成函數 (output 是某個結果,不是函數) - apply, identity 

在做了上述的這個分類之後,我有一個小小的新發現:其實組合函數還有一些不在這八個 combinator 裡的,分別是 some-fn 與 every-pred