Skip to content

Functional

函数式编程是通过应用和组合函数构建程序的编程范式。 它是一种声明式编程范式,其中函数定义是表达式树,每个表达式返回一个值,而不是改变程序状态的命令式语句序列。

Languages

Haskell

  • Lazy
  • Type Inference

Examples

List
[2^n | n <- [1..10], 2^n >= 10, 2^n < 100]
[x | x <- "outrageous", not (x `elem` "aeiou")]
[[x * y | y <- [1..5]] | x <- [1..5]]
Tuple
fst (1, "two")
snd (1, "two")

let numbers = [1..3]
let words = ["one", "two", "three"]
let pairs = zip numbers words
[(fst p, fst q) | p <- pairs, q <- pairs, fst p < fst q, length (snd p) > length (snd q)]
Type
:t Char
:t 3
3 :: Int
3 :: Double
:t head

f :: [Int] -> Int
f ls = head ls + length ls

dividesEvenly :: Int -> Int -> Bool
dividesEvenly x y = (y `div` x) * x == y

OCaml

Design Patterns

Monad

  • NumberWithLogs / Writer 累积 logs 数据
  • Option 可能缺失的值
  • Future / Promise 可能之后才有效的值
function getNickname(): Option<string> {
  const user: Option<User> = getCurrentUser();
  const userPet: Option<Pet> = run(user, getPet);
  const userPetNickname: Option<string> = run(userPet, getNickname);
  return userPetNickname;
}

也是 Rust 内置的语法规则

Functor