功能编程:什么是“不当列表”? [英] Functional Programming: what is an "improper list"?

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

问题描述

有人可以解释什么是不正确的列表?



注意:感谢所有!所有你们摇滚!

解决方案

我认为@ Vijay的答案是迄今为止最好的答案,我只是打算Erlangify它。 / p>

Erlang中的对(cons单元格)写为 [Head | Tail] ,而nil写为 [] 。对于头尾是什么而不是限制,但是如果您使用尾部链接更多的cons单元格,您将获得列表。如果最终的尾巴是 [] ,那么你得到一个正确的列表。对于列表的特殊语法支持,正确的列表

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

写为

  [1,2,3] 

和不正确的列表

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

写为

  [1,2,3 | 4] 

所以你可以看到差异。与正确/不正确的列表匹配相当容易。所以长度函数 len 为正确的列表:

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

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

  last_tail([_ | T]) - > last_tail(T); 
last_tail(尾) - >尾巴。 %将匹配任何尾部

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


Could somebody explain what an "improper list" is?

Note: Thanks to all ! All you guys rock!

解决方案

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

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|[]]]]

is written as

[1,2,3]

and the improper list

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

is written as

[1,2,3|4]

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.

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

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天全站免登陆