infinite lists, lazy evaluation and length

后端 未结 3 1135
南方客
南方客 2021-01-24 21:27

Haskell noob here: I\'m still trying to understand the mechanics of the language, so if my question is plain stupid, forgive me and point me to some link which I can learn from

3条回答
  •  故里飘歌
    2021-01-24 22:09

    is length actually iterating the whole list to give a response?

    Yes.

    I guess length is to be avoided every time I try to implement something working well with the lazy evaluation

    Not just that, it also gives you bad runtimes when laziness isn't a factor (being O(n) in cases where an O(1) check often suffices1), so you should avoid it most of the time in general.

    how can I improve my example to work with infinite lists?

    You don't need to check whether the length of the list is less than n, you just need to check whether it's zero. And that you can do with a simple pattern match.


    1 For example something like f xs | length xs >= 2 = ..., which is O(n), can be replaced with f (x1 : x2 : xs) = ..., which is O(1).

提交回复
热议问题