How do I use fix, and how does it work?

前端 未结 4 1410
暗喜
暗喜 2020-11-28 19:46

I was a bit confused by the documentation for fix (although I think I understand what it\'s supposed to do now), so I looked at the source code. That left me m

4条回答
  •  醉话见心
    2020-11-28 20:25

    How I understand it is, it finds a value for the function, such that it outputs the same thing you give it. The catch is, it will always choose undefined (or an infinite loop, in haskell, undefined and infinite loops are the same) or whatever has the most undefineds in it. For example, with id,

    λ <*Main Data.Function>: id undefined
    *** Exception: Prelude.undefined
    

    As you can see, undefined is a fixed point, so fix will pick that. If you instead do (\x->1:x).

    λ <*Main Data.Function>: undefined
    *** Exception: Prelude.undefined
    λ <*Main Data.Function>: (\x->1:x) undefined
    [1*** Exception: Prelude.undefined
    

    So fix can't pick undefined. To make it a bit more connected to infinite loops.

    λ <*Main Data.Function>: let y=y in y
    ^CInterrupted.
    λ <*Main Data.Function>: (\x->1:x) (let y=y in y)
    [1^CInterrupted.
    

    Again, a slight difference. So what is the fixed point? Let us try repeat 1.

    λ <*Main Data.Function>: repeat 1
    [1,1,1,1,1,1, and so on
    λ <*Main Data.Function>: (\x->1:x) $ repeat 1
    [1,1,1,1,1,1, and so on
    

    It is the same! Since this is the only fixed point, fix must settle on it. Sorry fix, no infinite loops or undefined for you.

提交回复
热议问题