Skip to content

Instantly share code, notes, and snippets.

@emanon-was
Last active November 6, 2017 12:23
Show Gist options
  • Save emanon-was/fc3f78f44f80555e9fcd05fc260d426f to your computer and use it in GitHub Desktop.
Save emanon-was/fc3f78f44f80555e9fcd05fc260d426f to your computer and use it in GitHub Desktop.
foldlとfoldl'の差
myFoldr :: (a -> b -> b) -> b -> [a] -> b
myFoldr _ a [] = a
myFoldr f a (x:xs) = f x $ myFoldr f a xs
myFoldr1 :: (a -> a -> a) -> [a] -> a
myFoldr1 f (x:xs) = myFoldr f x xs
myFoldl :: (b -> a -> b) -> b -> [a] -> b
myFoldl _ a [] = a
myFoldl f a (x:xs) = myFoldl f (f a x) xs
myFoldl' :: (b -> a -> b) -> b -> [a] -> b
myFoldl' _ a [] = a
myFoldl' f a (x:xs) = seq a' myFoldl' f a' xs
where a' = f a x
myFoldl1 :: (a -> a -> a) -> [a] -> a
myFoldl1 f (x:xs) = myFoldl f x xs
myFoldl1' :: (a -> a -> a) -> [a] -> a
myFoldl1' f (x:xs) = myFoldl' f x xs
sumTest :: (Num a) => [a] -> a
sumTest = myFoldl1 (+)
-- sumTest [1..10000000]
-- 50000005000000
-- (6.61 secs, 2422963880 bytes)
sumTest' :: (Num a) => [a] -> a
sumTest' = myFoldl1' (+)
-- sumTest' [1..10000000]
-- 50000005000000
-- (2.87 secs, 2003390168 bytes)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment