为什么函数式语言如此大量使用列表?

sti*_*oob 5 functional-programming list

我的意思是列表对其他数据结构有哪些优势,使其在函数式语言中几乎不可避免?

Tha*_*you 12

"没有勺子."

如果我告诉你没有字符串那么怎么办?仅存在单个字符列表.

如果我告诉你没有列表这样的东西怎么办?只有对.

; construct a pair of a and b
(cons 'a 'b)           ; => ('a 'b)

; get the first element of the pair
(first (cons 'a 'b))   ; => 'a

; get the second element of the pair
(second (cons 'a 'b))  ; => 'b

; create a "list"
(define x (cons 'a (cons 'b (cons 'c (cons 'd (cons 'e null))))))
; => ('a ('b ('c ('d ('e ())))))

; get the third element in the "list", x
(first (second (second x)))
; => 'c
Run Code Online (Sandbox Code Playgroud)

如果我告诉你没有成对的东西呢?只有lambdas.

(define (cons x y)
  (? (f) (f x y)))

(define (first p)
  (p (? (x y) x)))

(define (second p)
  (p (? (x y) y)))
Run Code Online (Sandbox Code Playgroud)

当然,这只是一种可能的实现方式.但重要的是要意识到这只是一种幻觉.

数据抽象真的很神奇.良好的语言允许您发明任何您希望使用的结构,并定义任何构造函数/选择器,使其适用于您的结构.有些语言比其他语言提供更多的语法糖.

列表很常见,因为作为程序员,我们经常处理有序的事物集合.其他常见类型是集合和地图.只是不要欺骗自己认为它是超级特殊的^,^