我可以与 where 子句中定义的函数进行模式匹配吗?

问题描述

我的目标是定义一个“proper”函数,它接受“Tree a”数据类型:

data Tree a = One a | Two (Tree a) (Tree a)

并使用递归定义生成所有适当的子树(即除自身之外的所有子树)。

我当前的代码如下所示:

proper :: Tree a -> [Tree a]
proper (One a) = []
proper (Two t1 t2) = [t1,t2] ++ proper' t1 ++ proper' t2
proper' (One a) = [One a]
proper' (Two t1 t2) = [t1,t2] ++ proper' t1 ++ proper' t2

我想知道是否有任何方法可以在 where 子句中获取 proper'。我曾尝试使用标准模式匹配和 case 表达式,但都导致解析器错误

注意:我之前有一个名为 subs 的函数,它生成树的所有子树,包括它自己,但我不允许在 proper 的定义中使用它

编辑:我解决了它,而不必定义新函数,但是 where 子句应该可以工作,我一定是在脚本中搞砸了。现在工作代码

proper :: Tree a -> [Tree a]
proper (One a) = []
proper (Two t1 t2) = [t1,t2] ++ proper t1 ++ proper t2

解决方法

是的,您可以:

proper :: Tree a -> [Tree a]
proper (One a) = []
proper (Two t1 t2) = [t1,t2] ++ proper' t1 ++ proper' t2
  where
    proper' (One a) = [One a]
    proper' (Two t1 t2) = [t1,t2] ++ proper' t1 ++ proper' t2

但是我看不出您需要什么 proper',因为此代码也能正常工作(与您的相反,不会复制叶子):

proper :: Tree a -> [Tree a]
proper (One a) = []
proper (Two t1 t2) = [t1,t2] ++ proper t1 ++ proper t2

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...