product of list iteratively

前端 未结 2 876
野的像风
野的像风 2021-01-25 02:35

I\'m trying to learn coding in Haskell.

I started with an easy example \"the product of a list\".

product :: [Integer] -> Integer  
product []     = 1         


        
2条回答
  •  说谎
    说谎 (楼主)
    2021-01-25 02:53

    Well in Haskell we don't have loops so iterative is relative, but here's the "functional iteration approach"

     product = foldl' (*) 1
    

    folds are the equivalent of loops in imperative languages. foldl' in particular is tail recursive and strict so it will run in constant space, similar to a loop.

    If we were to write it explicitly

     product = go 1
       where go accum (x:xs) = go (accum * x) xs
             go accum _      = accum -- Subtle performances
                                     -- differences with strictness
    

    This is still recursive, but will compile to similar assembly.

提交回复
热议问题