Haskell笔记 (19)—— Guard

guard跟在函数名和参数之后,用管道符号表示:

myCompare :: (Ord a) => a -> a -> Ordering  

myCompare a b
    | a < b = LT
    | a == b = EQ
    | otherwise = GT    

guard长得和pattern类似,pattern检查输入是否符合这个pattern,而guard则会计算布尔表达式,返回TrueFalse。如果返回值是True,则执行等号后面的函数体部分。

看另外一个例子:

Capture

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!

《Haskell笔记 (19)—— Guard》有2个想法

发表评论

邮箱地址不会被公开。 必填项已用*标注

This site uses Akismet to reduce spam. Learn how your comment data is processed.