我是Haskell的新手,目前正在从事我的第一个项目。我编写了一个函数,该函数根据对另一个函数的调用返回一些内容,然后再次调用该函数(因此它是递归的)。
function :: a -> a
function a
| null (recursive call) = a
| otherwise = head (same recursive call)
我怎样才能只进行一次递归调用并使用两次结果(作为条件和“返回值”的一部分)?
function a
| null recCall = a
| otherwise = head recCall
where recCall = recursive call
但这不是一个好方法。避免使用head
,tail
,!!
。通常,有一种叫做“布尔盲”的东西:使用布尔值意味着程序基本上会忘记基于逻辑的含义,这意味着您需要重新引入它,这会使您的程序既冗长又不可靠。
最好立即在递归结果上使用模式匹配:
function a = case recursive call of
[] -> a
(h:_) -> h
这也可以用模式保护语法编写
function a
| (h:_) <- recursive call = h
| otherwise = a
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句