Functional programming is a programming paradigm — a style of building the structure and elements of computer programs — that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data — Wikipedia
y=f(x)
def partial[A,B,C](a: A, f: (A, B) => C): B => C =
(b: B) => f(a, b)
def currying[A,B,C](f: (A, B) => C): A => B => C =
a => b => f(a, b)
def uncurrying[A,B,C](f: A => B => C): (A, B) => C =
(a, b) => f(a)(b)
def compose[A,B,C](f: B => C, g: A => B): A => C =
a => f(g(a))
sealed trait List[+A]
case object Nil extends List[Nothing]
case class Cons[+A](head: A, tail: List[A]) extends List[A]
sealed trait Option[+A]
case class Some[+A](get: A) extends Option[A]
case object None extends Option[Nothing]
sealed trait Either[+E,+A]
case class Left[+E](get: E) extends Either[E,Nothing]
case class Right[+A](get: A) extends Either[Nothing,A]
def sum(ints: List[Int]): Int = ints match {
case Nil => 0
case Cons(x,xs) => x + sum(xs)
}
def factorial2(n: Int): Int = {
var acc = 1
var i = n
while (i > 0) { acc *= i; i -= 1 }
acc
}
def factorial(n: Int): Int = {
@annotation.tailrec
def go(n: Int, acc: Int): Int =
if (n <= 0) acc
else go(n-1, n*acc)
go(n, 1)
}
FP 和 OOP 最根本的区别是什么呢?我认为是思维方式的不同:
OOP 是对现实世界的抽象,是归纳法。这个就不展开了…
而 FP 的核心应该是 Composability,是演绎法。像Minecraft、乐高这样的游戏、玩具,首先有一些基本的、可组合的模块,玩家可以自由组合,从而拥有无限可能性。函数式编程中的 Composability 更多的是抽象出的类型之间的转化:
函数式编程对内部的“pure”和对外部的“side effect”与一句话有异曲同工之妙 –
在组织内部不会有成果出现,一切成果都是发生在组织外部。