了解绑定和模式匹配 [英] Understanding binding and pattern matching

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

问题描述

我阅读了关于`let 5 = 10` 的问题,我没有使用任何让我在这里,在我的例子中,我写的代码在一个文件中,并执行它,所以我的问题还没有回答,没有答案对我有用。



我今天就[罕见的模式匹配] [1]提出了一个类似的问题,我们的一个朋友正在向我们讲授Haskell函数式编程的基础,并且他开始写下我见过的最稀有的东西:



他从一些不太好的东西开始,但很酷:

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

并在前奏中显示:

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

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

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

什么!?在课堂上,每个人都认为,确实会出错,但甚至没有编译的代码,然后运行:

 前奏> x 
10
前奏> 4
4
前奏> True
True


解决方案 let 使用 lazy 模式引入定义的公式。

在任何模块中,所有顶级定义都位于其中

  module Main其中
- ^^^^^

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

main :: IO()
main = putStrLnhello!

上述程序将打印出hello,如预期的那样。与(x,y)匹配的模式会严格分歧,但由于它是懒惰的,它不会 - undefined 表达式永远不会被评估。



在GHCi中键入的定义也隐含在 let p>

知道了这个之后,问题中提到的问题恰恰就是 let 5 = 10 的问题。


I read the question About `let 5 = 10` 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.

I made a similar question today about [rare Pattern Matching][1], a friend of us is teaching to us the basis of Functional Programming in Haskell, and he started to write the most rarest thing I ever saw:

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

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

and shows in the prelude:

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

解决方案

Both where and let introduce defining equations using lazy patterns.

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!"

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.

Definitions typed in GHCi are also under an implicit let.

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

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

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