summaryrefslogtreecommitdiffhomepage
path: root/haskell.html.markdown
diff options
context:
space:
mode:
authorAdam <adam@adambard.com>2013-07-02 11:00:30 -0700
committerAdam <adam@adambard.com>2013-07-02 11:00:30 -0700
commit94bd7fc1ee62c255f1f1c223c15cefc47e4b7820 (patch)
tree7a92399c979587c789bec519c6f04f4f0dc50155 /haskell.html.markdown
parentdceba637b3f86026c752bb8a96efba914bd9f576 (diff)
Added more on folds wrt replacing loops
Diffstat (limited to 'haskell.html.markdown')
-rw-r--r--haskell.html.markdown15
1 files changed, 14 insertions, 1 deletions
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 <fn> <initial value> <list>
+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
----------------------------------------------------