简体   繁体   English

从具有相关值的函数中删除显式递归

[英]Remove explicit recursion from function with dependent values

I have the following Haskell function which uses explicit recursion: 我有以下Haskell函数,它使用显式递归:

f :: [a] -> [a]
f (a:b:xs) = g a b : f (g a b : xs)
  where
    g :: a -> a -> a
f (_:[])   = []
f []       = []

Note that the recursive call depends on the value calculated in the step before (by g ). 请注意,递归调用取决于之前步骤(通过g )计算的值。

Is there a way to remove the explicit recursion and if so, how? 有没有办法删除显式递归,如果是,如何?

Your function is exactly a fold that emits intermediate values. 您的函数恰好是一个发出中间值的折叠。 In Haskell this is called a scan . 在Haskell中,这称为扫描 Specifically, scanl1 is equivalent to your f except the first element. 具体来说,除第一个元素外, scanl1相当于你的f

f = drop 1 . scanl1 g

use tail recursion, ghc can optimaze it 使用尾递归,ghc可以对它进行优化

f (a:b:xs) acc = f (g a b : xs) (g a b : acc)
f _ acc = reverse acc

and call so 并打电话给

f myList []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM