Haskell 模式匹配 - 它是什么? [英] Haskell pattern matching - what is it?
问题描述
Haskell 中的模式匹配是什么?它与保护方程有什么关系?
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.
有人标记为家庭作业.我不再上学了,我只是在学习 Haskell,我正在努力理解这个概念.纯粹出于兴趣.
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.
推荐答案
简而言之,模式就像定义数学中的分段函数.您可以使用模式为不同的参数指定不同的函数体.当您调用函数时,通过将实际参数与各种参数模式进行比较来选择适当的主体.阅读Haskell 简介了解更多信息.
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.
比较:
使用等效的 Haskell:
with the equivalent 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)
或 Just x
.在分段定义中,基于 =
或 ∈
关系的条件(基本上,说某物是"某物的条件)成为模式.警卫允许更一般的条件.我们可以重写 fib
来使用守卫:
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屋!