Correct way to add an element to the end of a list?

前端 未结 2 627
离开以前
离开以前 2021-01-22 13:12

I was reading on this Haskell page about adding an element to the end of a List.

Using the example, I tried it out for my self. Given the following Li

2条回答
  •  北海茫月
    2021-01-22 13:28

    ++ [x] is the correct way to add an element to the end of a list, but what the comment is saying is that you shouldn't add elements to the end of a list.

    Due to the way lists are defined, adding an element at the end always requires making a copy of the list. That is,

    xs ++ ys
    

    needs to copy all of xs but can reuse ys unchanged.

    If xs is just one element (i.e. we're adding to the beginning of a list), that's no problem: Copying one element takes practically no time at all.

    But if xs is longer, we need to spend more time in ++.

    And if we're doing this repeatedly (i.e. we're building up a big list by continually adding elements to the end), then we need to spend a lot of time making redundant copies. (Building an n-element list in this way is an O(n2) operation.)

    If you need to do this, there is usually a better way to structure your algorithm. For example, you can build your list in reverse order (adding elements at the beginning) and only call reverse at the end.

提交回复
热议问题