Sunday, February 22, 2015

HASKELL FOLDL INTRODUCTION

HASKELL FOLDL INTRODUCTION

REVISED: Saturday, February 10, 2024




I. FOLDL 

foldl saves a lot of code. We could do a "Copy Paste" of the following two functions and then do a "File, Save As" facProd.hs to our working directory.

myProduct :: (Num a) => [a] -> a
myProduct = foldl (*) 1

myFactorial :: Int -> Int
myFactorial n = myProduct [1..n]

GHCi, version 9.8.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude>

Prelude>  :load facProd
[1 of 1] Compiling Main             ( facProd.hs, interpreted )
Ok, modules loaded: Main.

And then call the myFactorial function which in turn calls the myProduct function.

myFactorial :: Int -> Int

Prelude>  myFactorial 3
6
Prelude>

Or we can just call the myProduct function and obtain the factorial.

myProduct :: (Num a) => [a] -> a

Prelude>  myProduct [1,2,3]
6
Prelude> 

With a little upfront thinking we could have written myProduct as myFactorial.

myFactorial :: (Num a) => [a] -> a
myFactorial = foldl (*) 1

However, notice what happened. Looking closely at both function signatures if we wanted the factorial using both of our original functions we only have to enter the function name and the one integer we want the factorial of.

myFactorial 3

Now we have to enter the function name and a list of all the integers that are part of the factorial sequence.

myProduct [1,2,3]

Our first choice using two functions was really the best choice. However, the point I am trying to make is, often foldl is used and we do not even know it is being used. It can be a behind the scenes player that does a lot of work for us.

Based on comments from the tutorial audience, use foldl' from the Data.List. It apparently does the same thing as the Prelude foldl; however, it appears to be more efficient. Use foldr on lists that might be infinite or where the fold is building up a data structure. Use foldl' if the list is known to be finite and comes down to a single value.

II. CONCLUSION

In this tutorial you have been introduced to the advantages of using Haskell foldl.

III. REFERENCES

Bird, R. (2015). Thinking Functionally with Haskell. Cambridge, England: Cambridge University Press.

Davie, A. (1992). Introduction to Functional Programming Systems Using Haskell. Cambridge, England: Cambridge University Press.

Goerzen, J. & O'Sullivan, B. &  Stewart, D. (2008). Real World Haskell. Sebastopol, CA: O'Reilly Media, Inc.

Hutton, G. (2007). Programming in Haskell. New York: Cambridge University Press.

Lipovača, M. (2011). Learn You a Haskell for Great Good!: A Beginner's Guide. San Francisco, CA: No Starch Press, Inc.

Thompson, S. (2011). The Craft of Functional Programming. Edinburgh Gate, Harlow, England: Pearson Education Limited.