guard
跟在函数名和参数之后,用管道符号表示:
myCompare :: (Ord a) => a -> a -> Ordering
myCompare a b
| a < b = LT
| a == b = EQ
| otherwise = GT
guard
长得和pattern
类似,pattern
检查输入是否符合这个pattern
,而guard
则会计算布尔表达式,返回True
或False
。如果返回值是True
,则执行等号后面的函数体部分。
看另外一个例子:
The first pattern specifies that if we try to take a 0 or negative number of elements, we get an empty list. Notice that we’re using _ to match the list because we don’t really care what it is in this case. Also notice that we use a guard, but without an otherwise part. That means that if n turns out to be more than 0, the matching will fall through to the next pattern.
当guard
没有otherwise
,如果都不匹配的话,就会执行下一个pattern
。
参考资料:
Guards, guards!。
看起来就像是分支语句……
嗯,那您现在觉得guard跟分支语句有什么区别吗?
这篇帖子(http://stackoverflow.com/questions/9345589/guards-vs-if-then-else-vs-cases-in-haskell)解释得很详细。可以参考!