Haskell模式匹配 - 它是什么? [英] Haskell pattern matching - what is it?
问题描述
我试过寻找一个简单的解释,但我还没有找到一个。
编辑:
有人标记为家庭作业。我不再去上学了,我只是在学习Haskell,我正试图理解这个概念。纯粹是出于兴趣。
简而言之,模式就像在数学中定义分段函数一样。您可以使用模式为不同的参数指定不同的函数体。当你调用一个函数时,通过比较实际参数和各种参数模式来选择合适的体。阅读 Haskell简介获取更多信息。
比较:
与等价的Haskell:
fib 0 = 1
fib 1 = 1
fib n | n> = 2
= fib(n-1)+ fib(n-2)
注意,分段函数中的 n ≥2成为Haskell版本中的一个守护程序,但其他两个条件仅仅是模式。模式是测试值和结构的条件,例如 x:xs
,(x,y,z)
或只需x
。在分段定义中,基于 =
或∈
关系的条件(基本上,说某事的条件是其他)变成模式。守卫允许更一般的条件。我们可以重写 fib
来使用警卫:
fib n | n == 0 = 1
| n == 1 = 1
| n> = 2 = fib(n-1)+ fib(n-2)
What is pattern matching in Haskell and how is it related to guarded equations?
I've tried looking for a simple explanation, but I haven't found one.
EDIT: Someone tagged as homework. I don't go to school anymore, I'm just learning Haskell and I'm trying to understand this concept. Pure out of interest.
In a nutshell, patterns are like defining piecewise functions in math. You can specify different function bodies for different arguments using patterns. When you call a function, the appropriate body is chosen by comparing the actual arguments with the various argument patterns. Read A Gentle Introduction to Haskell for more information.
Compare:
with the equivalent Haskell:
fib 0 = 1
fib 1 = 1
fib n | n >= 2
= fib (n-1) + fib (n-2)
Note the "n ≥ 2" in the piecewise function becomes a guard in the Haskell version, but the other two conditions are simply patterns. Patterns are conditions that test values and structure, such as x:xs
, (x, y, z)
, or Just x
. In a piecewise definition, conditions based on =
or ∈
relations (basically, the conditions that say something "is" something else) become patterns. Guards allow for more general conditions. We could rewrite fib
to use guards:
fib n | n == 0 = 1
| n == 1 = 1
| n >= 2 = fib (n-1) + fib (n-2)
这篇关于Haskell模式匹配 - 它是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!