是=假?了解绑定和模式匹配 [英] Is True = False? Understanding binding and pattern matching

查看:73
本文介绍了是=假?了解绑定和模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的一个朋友正在用Haskell向我们教授函数式编程的基础知识,他开始写我见过的最稀有的东西:

A friend of us is teaching to us the basics of functional programming in Haskell, and he started to write the rarest thing I ever saw:

他开始时并没有那么令人惊讶,但很酷:

He started with something not so amazing, but pretty cool:

(x,y) = (10,20)
(z:zs) = 0 : [1..]

并在前奏中显示:

prelude> x
10
prelude> z
0
prelude> takeN 3 zs
[1,2,3]

到目前为止,很好...我不知道您可以绑定这样的值

so far, so good... I didn't know you could bind the values like that

(x,y) = (10,20)
(z:zs) = 0 : [1..]
True = False -- HERE

什么!?班上的每个人都认为,确定会出问题,但甚至编译的代码都没有,然后它会运行:

What!? Everyone in the class thought, ok, something will go wrong, but not even the code compiled, then it runs:

prelude> x
10
prelude> 4
4
prelude> True
True

(我读了一个问题`let 5 = 10`是做什么的?这不是赋值操作吗? ?并且我在这里不使用任何让步,在我的示例中,我将代码写入文件中并执行它,因此我的问题尚未得到解答,所有这些回答均对我没有用.)

(I read the question What does `let 5 = 10` do? Is it not an assignment operation? and I'm not using any let here, in my example I write the code in a file and the execute it, so my question is not answered yet, none of that answers are useful for me.)

推荐答案

wherelet都使用 lazy 模式引入了定义方程式.

Both where and let introduce defining equations using lazy patterns.

在任何模块中,所有顶级定义都在where下.

In any module, all the top-level definitions are under a where.

module Main where
         -- ^^^^^

x, y :: Int
(x, y) = undefined

main :: IO ()
main = putStrLn "hello!"

以上程序将按预期打印"hello".如果严格,则与(x, y)匹配的模式会有所不同,但是由于它是惰性的,因此不会-undefined表达式永远不会被求值.

The above program will print "hello", as intended. The pattern matching against (x, y) would diverge if it were strict, but since it is lazy it does not -- the undefined expression never gets evaluated.

在GHCi中键入的定义也位于隐式let下.

Definitions typed in GHCi are also under an implicit let.

知道这一点后,问题中提到的问题恰好是 let 5 = 10 问题.

After knowing this, the issue mentioned in the question is exactly the one in the let 5 = 10 question.

这篇关于是=假?了解绑定和模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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