'未定义'如何在Haskell中工作 [英] how does 'undefined' work in Haskell

查看:115
本文介绍了'未定义'如何在Haskell中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇Haskell中的'undefined'值。它很有趣,因为你可以把它放在任何地方,而Haskell会很开心。以下全部为a-ok

  [1.0,2.0,3.0,undefined] :: [Float] 
[ 1,2,3 undefined,102312] :: [Int]
(CATS!,undefined)::(String,String)
....以及更多

undefined如何在引擎盖下工作?什么使得拥有每种数据类型的数据成为可能?我可以定义一个像这样的值,我可以放在任何地方,或者这是一些特殊情况吗?

解决方案

关于 undefined 没有什么特别的。这只是一个特殊的价值 - 你可以用无限循环,崩溃或段错代表它。编写它的一种方法是崩溃:

  undefined :: a 
undefined | False = undefined

或循环:

  undefined = undefined 

这是一个特殊的值,可以是任何类型的元素。

由于Haskell是懒惰的,您仍然可以在计算中使用这些值。例如:

 >长度[未定义,未定义] 
2

但除此之外,它只是一个自然结果多态性和非严格性。

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

[1.0, 2.0, 3.0 , undefined]  ::[Float]
[1, 2 ,3 undefined, 102312] :: [Int]
("CATS!", undefined)  :: (String, String)
....and many more

How does undefined work under the hood? What makes it possible to have data that is of every data type? Would it be possible for me to define a value like this that I can put everywhere, or is this some special case?

解决方案

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.

这篇关于'未定义'如何在Haskell中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆