Would the ability to detect cyclic lists in Haskell break any properties of the language?

后端 未结 2 617
慢半拍i
慢半拍i 2021-01-07 19:44

In Haskell, some lists are cyclic:

ones = 1 : ones

Others are not:

nums = [1..]

And then there are things

2条回答
  •  死守一世寂寞
    2021-01-07 20:05

    In the general case, no you can't identify a cyclic list. However if the list is being generated by an unfold operation then you can. Data.List contains this:

    unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
    

    The first argument is a function that takes a "state" argument of type "b" and may return an element of the list and a new state. The second argument is the initial state. "Nothing" means the list ends.

    If the state ever recurs then the list will repeat from the point of the last state. So if we instead use a different unfold function that returns a list of (a, b) pairs we can inspect the state corresponding to each element. If the same state is seen twice then the list is cyclic. Of course this assumes that the state is an instance of Eq or something.

提交回复
热议问题