简体   繁体   English

Haskell罕见的模式匹配

[英]Haskell rare pattern matching

In haskell, I can do: 在haskell,我可以这样做:

s@"Hello" = s 

The result is: 结果是:

>s
>"

It begins to print the String but never ends, what is goin on? 它开始打印字符串,但永远不会结束,是什么?

The @"Hello" is irrelevant here, all it does is fix the type to String . @"Hello"在这里是无关紧要的,它只是将类型修复为String You get the same behaviour with 你得到了同样的行为

s :: String
s = s

Which is semantically equivalent to 这在语义上等同于

s' :: String
s' = undefined

which gives the result 给出了结果

Prelude> s'
"*** Exception: Prelude.undefined

What I mean by “semantically equivalent” is, both s and s' are examples of bottom values , ie values from that “sin bin of error values any type contains, thanks to non-strictness”. 我所说的“语义等价”是指, ss'都是底值的例子,即“任何类型包含的错误值的sin bin的值,由于非严格性”。 As soon as you hit a bottom value, the pure Haskell language is basically powerless and has give in to, well, undefined , “impure behaviour”, like letting you wait forever or throwing an exception. 一旦你达到最低价值,纯粹的Haskell语言基本上是无能为力的,并且已经屈服于未定义的 “不纯行为”,就像让你永远等待或抛出异常一样。

However, again thanks to non-strictness, this needs not necessarily happen. 然而,再次感谢非严格性,这不一定需要发生。 When printing a value, the first thing that happens is, the Show instance is invoked and asked to produce a string. 打印值时,首先发生的事情是调用Show实例并要求生成一个字符串。 A Haskell string is a lazy list. Haskell字符串是一个惰性列表。 And the show of any string begins with " , therefore even if the string itself is utterly undefined, show will manage to produce that one character. 并且任何字符串的show都以"开头" ,因此即使字符串本身完全未定义, show也会设法生成那个字符。

We can observe this more sheltered with 我们可以观察到更多的庇护

Prelude> head $ show s
'"'

In let s and top level expressions everything on the left-hand side of the = is in scope on the right-hand side. let和顶级表达式中, =左侧的所有内容都在右侧的范围内。 So you've created a looping "bottom" value. 所以你创建了一个循环的“底部”值。

Notice this behaves the same way: 请注意,这行为方式相同:

Prelude> let s = (s::String)
Prelude> s
"

That's because (simplifying) print on String is defined something equivalent to: 这是因为(简化)在Stringprint定义相当于:

printString chars = putChar '"' >> mapM_ putChar chars

Because chars is a loop the mapM_ putChar chars appears to hang. 因为chars是一个循环, mapM_ putChar chars似乎挂起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM