为什么函数式语言如此大量地使用列表? [英] Why do functional languages make such heavy use of lists?

查看:83
本文介绍了为什么函数式语言如此大量地使用列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是说list在其他数据结构上具有什么优势,这使得在功能语言中它几乎是不可避免的吗?

I mean what advantages does list has on other data structures which make it almost inevitable in functional languages?

推荐答案

没有汤匙."

"There is no spoon."

如果我告诉您没有字符串之类的东西怎么办?仅存在单个字符的列表.

What if I told you there is no such thing as strings? There exists only lists of single characters.

然后,如果我告诉您没有清单,该怎么办?只有一对.

Then what if I told you there is no such thing as a list? There exists only pairs.

; 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

现在,如果我告诉您没有配对的话该怎么办?只有lambda.

Now what if I told you there is no such thing as pairs? There exists only lambdas.

(define (cons x y)
  (λ (f) (f x y)))

(define (first p)
  (p (λ (x y) x)))

(define (second p)
  (p (λ (x y) y)))

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

Of course this is just one possible implementation. But it's important to realize that it's all just an illusion.

数据抽象确实是神奇的.好的语言可以让您发明任何想要使用的结构,并定义任何使其对您的结构有用的构造函数/选择器.一些语言比其他语言提供更多的语法糖.

Data abstraction is truly magical. Good languages allow you to invent any structure you wish to work with and define any constructors/selectors that make it useful to work with your structure. Some languages just offer more syntactic sugar than others.

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

Lists are common because, as programmers, we often deal with ordered collections of things. Other common types are Sets and Maps. Just don't fool yourself into thinking it's anything super special ^,^

这篇关于为什么函数式语言如此大量地使用列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆