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

前端 未结 2 632
离开以前
离开以前 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:14

    It's the correct way in that all ways of doing it must reduce to at least that much work. The problem is wanting to append to the end of a list at all. That's not an operation that's possible to do efficiently with immutable linked lists.

    The better approach is figuring out how to solve your specific problem without doing that. There are a lot of potential approaches. Picking the right one depends on the details of what you're doing. Maybe you can get away with just using laziness correctly. Maybe you are best off generating the list backwards and then reversing it once at the end. Maybe you're best off using a different data structure. It all depends on your specific use case.

提交回复
热议问题