模式与Haskell中的函数匹配

时间:2018-04-01 23:48:16

标签: haskell

我注意到Haskell的以下特点:

#include <math.h> //for M_PI
double coseno(float x){
    while(x<0) x+=2*M_PI;
    while(x>2*M_PI) x-=2*M_PI;
    double t = 1;
    double cos= t;
    for ( int a=1; a<40; ++a)
    {
        double mult = -x*x/((2*a)*(2*a-1));
        t *= mult;
        cos += t;
    }
    return cos;
}

这是完全正常运行的代码,它将返回二叉树中的叶子数。但是,如果尝试调用函数 data Tree a = Empty | Branch a (Tree a) (Tree a) deriving (Show, Eq) leaf:: a->Tree a leaf x = Branch x Empty Empty findNumL:: Tree a->Integer findNumL (Empty) = 0 findNumL (Branch x Empty Empty) = 1 findNumL (Branch x left right) = (findNumL left) + (findNumL right) 而不是leaf x,则模式识别会中断,使Branch x Empty Empty的定义远没有那么有用。有没有办法绕过这个问题并在模式匹配中使用leaf x

1 个答案:

答案 0 :(得分:2)

您可以使用语言扩展程序PatternSynonyms

{-# LANGUAGE PatternSynonyms #-}

data Tree a = Empty  | Branch a (Tree a) (Tree a) deriving (Show, Eq)
pattern Leaf a = Branch a Empty Empty

findNumL:: Tree a->Integer
findNumL (Empty) = 0
findNumL (Leaf x) = 1
findNumL (Branch x left right) = (findNumL left) + (findNumL right)

Live example