Functional Programming: what is an “improper list”?

前端 未结 9 1028
遥遥无期
遥遥无期 2020-11-27 04:38

Could somebody explain what an \"improper list\" is?

Note: Thanks to all ! All you guys rock!

9条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 04:49

    I think it's easier to explain this using Scheme.

    A list is a chain of pairs that end with an empty list. In other words, a list ends with a pair whose cdr is ()

    (a . (b . (c . (d . (e . ()))))) 
    
    ;; same as
    
    (a b c d e)
    

    A chain of pairs that doesn't end in the empty list is called an improper list. Note that an improper list is not a list. The list and dotted notations can be combined to represent improper lists, as the following equivalent notations show:

     (a b c . d)
     (a . (b . (c . d)))
    

    An example of a usual mistake that leads to the construction of an improper list is:

    scheme> (cons 1 (cons 2 3))
    (1 2 . 3)
    

    Notice the dot in (1 2 . 3)---that's like the dot in (2 . 3), saying that the cdr of a pair points to 3, not another pair or '(). That is, it's an improper list, not just a list of pairs. It doesn't fit the recursive definition of a list, because when we get to the second pair, its cdr isn't a list--it's an integer.

    Scheme printed out the first part of the list as though it were a normal cdr-linked list, but when it got to the end, it couldn't do that, so it used "dot notation."

    You generally shouldn't need to worry about dot notation, because you should use normal lists, not improper list. But if you see an unexpected dot when Scheme prints out a data structure, it's a good guess that you used cons and gave it a non-list as its second argument--something besides another pair or ().

    Scheme provides a handy procedure that creates proper lists, called list. list can take any number of arguments, and constructs a proper list with those elements in that order. You don't have to remember to supply the empty list---list automatically terminates the list that way.

    Scheme>(list 1 2 3 4)
    (1 2 3 4)
    

    Courtesy: An Introduction to Scheme

提交回复
热议问题