From 94bd7fc1ee62c255f1f1c223c15cefc47e4b7820 Mon Sep 17 00:00:00 2001 From: Adam Date: Tue, 2 Jul 2013 11:00:30 -0700 Subject: Added more on folds wrt replacing loops --- haskell.html.markdown | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) (limited to 'haskell.html.markdown') diff --git a/haskell.html.markdown b/haskell.html.markdown index 84b8f263..bc712505 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -245,7 +245,7 @@ case args of _ -> putStrLn "bad args" -- Haskell doesn't have loops because it uses recursion instead. --- map a function over every element in an array +-- map calls a function over every element in an array map (*2) [1..5] -- [2, 4, 6, 8, 10] @@ -258,6 +258,19 @@ for [0..5] $ \i -> show i -- we could've written that like this too: for [0..5] show +-- You can use foldl or foldr to reduce a list +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- This is the same as +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- foldl is left-handed, foldr is right- +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- This is now the same as +(2 * 3 + (2 * 2 + (2 * 1 + 4) + ---------------------------------------------------- -- 7. Data Types ---------------------------------------------------- -- cgit v1.2.3