how does 'undefined' work in Haskell

后端 未结 6 1400
广开言路
广开言路 2021-02-05 04:23

I\'m curious about the \'undefined\' value in Haskell. Its interesting because you can put it just about anywhere, and Haskell will be happy. The following are all a-ok

6条回答
  •  执笔经年
    2021-02-05 04:41

    There's nothing really special about undefined. It is just an exceptional value -- you could represent it with an infinite loop, or a crash, or a segfault. One way to write it is as a crash:

    undefined :: a
    undefined | False = undefined
    

    Or a loop:

    undefined = undefined
    

    It is an exceptional value that can be an element of any type.

    Since Haskell is lazy you can still use such values in computations. E.g.

     > length [undefined, undefined]
     2
    

    But otherwise, it is just a natural consequence of polymorphism and non-strictness.

提交回复
热议问题