简体   繁体   中英

Remove explicit recursion from function with dependent values

I have the following Haskell function which uses explicit recursion:

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 ).

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 . Specifically, scanl1 is equivalent to your f except the first element.

f = drop 1 . scanl1 g

use tail recursion, ghc can optimaze it

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

and call so

f myList []

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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