函数式编程:什么是“不正确的列表"? [英] Functional Programming: what is an "improper list"?

查看:19
本文介绍了函数式编程:什么是“不正确的列表"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下什么是不正确的列表"?

Could somebody explain what an "improper list" is?

注意:谢谢大家!你们都摇滚!

Note: Thanks to all ! All you guys rock!

推荐答案

我认为@Vijay 的答案是迄今为止最好的答案,我只是打算将其 Erlangify.

I think @Vijay's answer is the best one so far and I just intend to Erlangify it.

Erlang 中的 Pairs (cons cell) 写成 [Head|Tail] 而 nil 写成 [].对于头部和尾部是什么没有限制,但是如果你使用尾部链接更多的 cons 单元,你会得到一个 list.如果最后的尾部是[],那么你会得到一个正确的列表.列表有特殊的语法支持,因为正确的列表

Pairs (cons cells) in Erlang are written as [Head|Tail] and nil is written as []. There is no restriction as to what the head and tail are but if you use the tail to chain more cons cells you get a list. If the final tail is [] then you get a proper list. There is special syntactic support for lists in that the proper list

[1|[2|[3|[]]]]

写成

[1,2,3]

和不正确的列表

[1|[2|[3|4]]]

写成

[1,2,3|4]

所以你可以看到差异.匹配正确/不正确的列表也相应容易.所以适当列表的长度函数 len :

so you can see the difference. Matching against proper/improper lists is correspondingly easy. So a length function len for proper lists:

len([_|T]) -> 1 + len(T);
len([]) -> 0.

我们明确匹配终止 [] 的地方.如果给出一个不正确的列表,这将产生一个错误.而返回列表最后一个尾部的函数 last_tail 也可以处理不正确的列表:

where we explicitly match for the terminating []. If given an improper list this will generate an error. While the function last_tail which returns the last tail of a list can handle improper lists as well:

last_tail([_|T]) -> last_tail(T);
last_tail(Tail) -> Tail.                 %Will match any tail

请注意,构建列表或与其匹配,就像您通常使用 [Head|Tail] 所做的那样检查尾部是否为列表,因此没有处理不正确列表的问题.很少需要不正确的列表,尽管你可以用它们做很酷的事情.

Note that building a list, or matching against it, as you normally do with [Head|Tail] does not check if the tail is list so there is no problem in handling improper lists. There is seldom a need for improper lists, though you can do cool things with them.

这篇关于函数式编程:什么是“不正确的列表"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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