Functional programming - standard symbols, diagrams, etc

你说的曾经没有我的故事 提交于 2019-11-30 14:55:24

There's a secret trick to functional programming.

  1. It's largely stateless, so the traditional imperative diagrams don't matter.

  2. Most of ordinary, garden-variety math notation is also stateless.

Functional design is more like algebra than anything else. You're going to define functions, and show that the composition of those functions produces the desired result.

Diagrams aren't as necessary because functional programming is somewhat simpler than procedural programming. It's more like conventional mathematical notation. Use mathematical techniques to show that your various functions do the right things.

Functional programmers are more into writing equations then writing diagrams. The game is called equational reasoning and it mostly involves

  • Substituting equals for equals

  • Applying algebraic laws

  • The occasional proof by induction

The idea is that you write really simple code that is "manifestly correct", then you use equational reasoning to turn it into something that is cleaner and/or will perform better. The master of this art is an Oxford professor named Richard Bird.

For example, if I want to simplify the Scheme expression

(append (list x) l)

I will subsitute equals for equals like crazy. Using the definition of list I get

(append (cons x '()) l)

Subsituting the body of append I have

(if (null? (cons x '())) 
    l
    (cons (car (cons x '())) (append (cdr (cons x '())) l)))

Now I have these algebraic laws:

(null? (cons a b)) == #f
(car   (cons a b)) == a
(cdr   (cons a b)) == b

and substituting equals for equals I get

(if #f
    l
    (cons x (append '() l))

With another law, (if #f e1 e2) == e2, I get

(cons x (append '() l))

And if I expend the definition of append again I get

(cons x l)

which I have proved is equal to

(append (list x) l)

I don't know much about functional programming, but here are two things I have run into

  • λ (lambda) is often used to denote a function
  • f ο g is used to indicate function composition
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!